{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Linux专项\n",
    "\n",
    "先写几个问号来概况下今天准备说的内容：（谜底自己解开，文中都有）\n",
    "\n",
    "1. **你知道`Ctrl+C`终止进程的本质吗？你知道`Kill -9 pid`的真正含义吗？**\n",
    "2. **你知道那些跨平台框架（Python，NetCore）在Linux下创建进程干了啥？**\n",
    "3. **你了解`僵尸进程`和`孤儿进程`的悲催生产史吗？`孤儿找干爹`，`僵尸送往生`想知道不？**\n",
    "4. **想知道创建子进程后怎么`李代桃僵`吗？`ps aux | grep xxx`的背后到底隐藏了什么？**\n",
    "5. **你了解Linux磁盘中p类型的文件到底是个啥吗？**\n",
    "6. **为什么要realase发布而不用debug直接部署?这背后的性能相差几何？**\n",
    "7. **还有更多进程间的`密密私语`等着你来查看哦～**\n",
    "\n",
    "关于帮助文档的说明：\n",
    "- 所有用到的系统函数你都可以使用`man`查看，eg：`man 2 pipe`\n",
    "- Python里面的方法你都可以通过`help`查看，eg：`help(os.pipe)`\n",
    "\n",
    "## 1.概念引入\n",
    "\n",
    "正式讲课之前，先说些基本概念，难理解的用程序跑跑然后再理解：**如有错误欢迎批评指正**\n",
    "\n",
    "**<a href=\"https://baike.baidu.com/item/并发\" target=\"_blank\">并发</a>** :一个时间段中有几个程序都处于已启动运行到运行完毕之间，且这几个程序都是在同一个处理机上运行，但任一个时刻点上只有一个程序在处理机上运行。\n",
    "\n",
    "**<a href=\"https://baike.baidu.com/item/并行\" target=\"_blank\">并行</a>** :当一个CPU执行一个线程时，另一个CPU可以执行另一个线程，两个线程互不抢占CPU资源，可以同时进行，这种方式我们称之为并行(Parallel)。（在同一个时间段内，两个或多个程序执行，有时间上的重叠）\n",
    "\n",
    "---\n",
    "\n",
    "通俗的举个例子：\n",
    "\n",
    "小明、小潘、小张、小康去食堂打饭，4个小伙子Coding了3天，饿爆了，现在需要1分钟内让他们都吃上饭，不然就有可怕的事情发生。\n",
    "\n",
    "按照正常的流程，1分钟可能只够他们一个人打饭，这不行啊，于是有了几种处理方法：\n",
    "\n",
    "**并发**：快快快，**一人先吃一口，轮着来，一直喂到你们都饱了**(只有一个食堂打饭的窗口)（单核CPU）\n",
    "\n",
    "**并行**：\n",
    "- 开了2~3个窗口，和上面处理一样，只是竞争的强度没那么大了\n",
    "- 开了4个窗口，不着急，一人一个窗口妥妥的\n",
    "\n",
    "---\n",
    "\n",
    "对于操作系统来说，**一个任务就是一个进程（Process）**，比如打开一个浏览器就是启动一个浏览器进程，打开两个浏览器就启动了两个浏览器进程。\n",
    "\n",
    "有些进程还不止同时干一件事，比如Word，它可以同时进行打字、拼写检查、打印等事情。**在一个进程内部，要同时干多件事，就需要同时运行多个“子任务”，我们把进程内的这些“子任务”称为线程（Thread）**。\n",
    "\n",
    "由于**每个进程至少要干一件事，所以，一个进程至少有一个线程**。像Word这种复杂的进程可以有多个线程，多个线程可以同时执行，多线程的执行方式和多进程是一样的，也是由操作系统在多个线程之间快速切换，让每个线程都短暂地交替运行，看起来就像同时执行一样。\n",
    "\n",
    "通俗讲：**线程是最小的执行单元，而进程由至少一个线程组成。`如何调度进程和线程，完全由操作系统决定，程序自己不能决定什么时候执行，执行多长时间`**\n",
    "\n",
    "---\n",
    "\n",
    "PS：进程5态下次正式讲程序的时候会说，然后就是==> 程序实战不会像今天这样繁琐的，Code很简单，但是不懂这些基本概念往后会吃很多亏，逆天遇到太多坑了，所以避免大家入坑，简单说说这些概念和一些偏底层的东西～看不懂没事，有个印象即可，以后遇到问题至少知道从哪个方向去解决"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.进程相关\n",
    "\n",
    "示例代码：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux</a>\n",
    "\n",
    "### 2.1.fork引入\n",
    "\n",
    "示例代码：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/base\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/base</a>\n",
    "\n",
    "(linux/unix)操作系统提供了一个`fork()`系统调用。普通的函数调用，调用一次，返回一次，但是`fork()`**一次调用，两次返回**。\n",
    "\n",
    "因为操作系统自动把父进程复制了一份，分别在父进程和子进程内返回。为了便于区分，操作系统是这样做的：**子进程永远返回0，而父进程返回子进程的ID**\n",
    "\n",
    "查看下帮助文档：\n",
    "```py\n",
    "import os\n",
    "\n",
    "help(os.fork)\n",
    "Help on built-in function fork in module posix:\n",
    "\n",
    "fork()\n",
    "    Fork a child process.\n",
    "    \n",
    "    Return 0 to child process and PID of child to parent process.\n",
    "```\n",
    "我们来跑个程序验证一下：（PID返回值如果小于0一般都是出错了）\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    print(\"准备测试～PID：%d\" % os.getpid())\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：PID：%d,PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：PID：%d,PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "结果：\n",
    "```\n",
    "准备测试～PID：11247\n",
    "父进程：PID：11247,PPID：11229\n",
    "子进程：PID：11248,PPID：11247\n",
    "```\n",
    "可以查看下这个进程是啥：\n",
    "![PPID.png](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725060305297-1803214924.png)\n",
    "\n",
    "这个指令如果还不熟悉，Linux基础得好好复习下了：<a href=\"https://www.cnblogs.com/dunitian/p/4822807.html\" target=\"_blank\">https://www.cnblogs.com/dunitian/p/4822807.html</a>，简单分析下吧：a是查看所有（可以联想ls -a），u是显示详细信息，x是把不依赖终端的进程也显示出来（终端可以理解为：人与机器交互的那些）\n",
    "\n",
    "技巧：指令学习可以递增式学习：`ps`，`ps a` `ps au` `ps aux` `ps ajx`\n",
    "\n",
    "现在验证一下复制一份是什么意思：（代码原封不动，只是在最下面添加了一行输出）\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    print(\"准备测试～PID：%d\" % os.getpid())\n",
    "    pid = os.fork() # 子进程被父进程fork出来后，在fork处往下执行\n",
    "    \n",
    "    if pid == 0:\n",
    "        print(\"子进程：PID：%d,PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：PID：%d,PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "    \n",
    "    print(\"PID:%d,我是卖报的小行家，大风大雨都不怕\" % os.getpid())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（父子进程的执行顺序是系统调度决定的）\n",
    "```\n",
    "准备测试～PID：13081\n",
    "父进程：PID：13081,PPID：9388\n",
    "PID:13081,我是卖报的小行家，大风大雨都不怕\n",
    "子进程：PID：13083,PPID：13081\n",
    "PID:13083,我是卖报的小行家，大风大雨都不怕\n",
    "```\n",
    "的确是Copy了一份，Code都一样（玩过逆向的应该知道，**这份Code其实就放在了`.text`（代码段）里面**）\n",
    "\n",
    "子进程被父进程fork出来后，在fork处往下执行（Code和父进程一样），这时候他们就为了抢CPU各自为战了\n",
    "\n",
    "最后验证一下：**各个进程地址空间中数据是完全独立的**（有血缘关系的则是：读时共享，写时复制，比如父子进程等）\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    num = 100\n",
    "    pid = os.fork()\n",
    "    # 子进程\n",
    "    if pid == 0:\n",
    "        num += 10\n",
    "    elif pid > 0:\n",
    "        num += 20\n",
    "\n",
    "    print(\"PID:%d，PPID：%d，Num=%d\" % (os.getpid(), os.getppid(), num))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（进程间通信下一节课会系统的讲，今天只谈Linux和概念）\n",
    "```\n",
    "PID:6369，PPID：6332，Num=120\n",
    "PID:6376，PPID：6369，Num=110\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "扩展：（简单了解下即可）\n",
    "1. **程序**：二进制文件（占用磁盘）\n",
    "2. **进程**：启动的程序（所有数据都在内存中，需要占用CPU、内存等资源）\n",
    "3. 进程是CPU、内存、I/0设备的抽象（**各个进程地址空间中数据是完全独立的**）\n",
    "4. 0号进程是Linux**内核进程**（这么理解：初代吸血鬼）\n",
    "5. 1号进程是用户进程，所有进程的创建或多或少和它有关系（`init` or `systemd`）\n",
    "6. 2号进程和1号进程一样，都是0号进程创建的，所有**线程调度**都和他有关系\n",
    "\n",
    "先看看Linux启动的图示：（图片来自网络）\n",
    "![2.Linux_Start](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725075809773-478928450.png)\n",
    "\n",
    "查看一下init进程\n",
    "![Ubuntu](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725081532394-1503236514.png)\n",
    "\n",
    "CentOS进行了优化管理～`systemd`\n",
    "![CentOS](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725081540780-1977663229.png)\n",
    "\n",
    "其实程序开机启动方式也可以知道区别了：`systemctl start mongodb.service` and `sudo /etc/init.d/ssh start`\n",
    "\n",
    "Win系列的0号进程：\n",
    "![win](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725081524339-1952364091.jpg)\n",
    "\n",
    "---\n",
    "\n",
    "第5点的说明：（以远程CentOS服务器为例）\n",
    "**pstree -ps**\n",
    "```shell\n",
    "systemd(1)─┬─NetworkManager(646)─┬─{NetworkManager}(682)\n",
    "           │                     └─{NetworkManager}(684)\n",
    "           ├─agetty(1470)\n",
    "           ├─auditd(600)───{auditd}(601)\n",
    "           ├─crond(637)\n",
    "           ├─dbus-daemon(629)───{dbus-daemon}(634)\n",
    "           ├─firewalld(645)───{firewalld}(774)\n",
    "           ├─lvmetad(483)\n",
    "           ├─master(1059)─┬─pickup(52930)\n",
    "           │              └─qmgr(1061)\n",
    "           ├─polkitd(627)─┬─{polkitd}(636)\n",
    "           │              ├─{polkitd}(639)\n",
    "           │              ├─{polkitd}(640)\n",
    "           │              ├─{polkitd}(642)\n",
    "           │              └─{polkitd}(643)\n",
    "           ├─rsyslogd(953)─┬─{rsyslogd}(960)\n",
    "           │               └─{rsyslogd}(961)\n",
    "           ├─sshd(950)───sshd(50312)───sshd(50325)───bash(50326)───pstree(54258)\n",
    "           ├─systemd-journal(462)\n",
    "           ├─systemd-logind(626)\n",
    "           ├─systemd-udevd(492)\n",
    "           └─tuned(951)─┬─{tuned}(1005)\n",
    "                        ├─{tuned}(1006)\n",
    "                        ├─{tuned}(1007)\n",
    "                        └─{tuned}(1048)\n",
    "```\n",
    "再看一个例子：\n",
    "```shell\n",
    "[dnt@localhost ~]$ pstree dnt -ps\n",
    "sshd(50325)───bash(50326)───pstree(54471)\n",
    "[dnt@localhost ~]$ pstree 50325 -ps\n",
    "systemd(1)───sshd(950)───sshd(50312)───sshd(50325)───bash(50326)───pstree(54489)\n",
    "```\n",
    "其实你可以在虚拟机试试干死1号进程，就到了登录页面了【现在大部分系统都不让你这么干了】\n",
    "**kill -9 1**\n",
    "```\n",
    "-bash: kill: (1) - 不允许的操作\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.僵尸进程和孤儿进程\n",
    "\n",
    "示例代码：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/base\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/base</a>\n",
    "\n",
    "先看看定义：\n",
    "\n",
    "**<a href=\"https://baike.baidu.com/item/孤儿进程\" target=\"_blank\">孤儿进程</a>** ：一个父进程退出，而它的一个或多个子进程还在运行，那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养，并由init进程对它们完成状态收集工作。\n",
    "\n",
    "**<a href=\"https://baike.baidu.com/item/僵尸进程\" target=\"_blank\">僵尸进程</a>** ：一个进程使用fork创建子进程，如果子进程退出，而父进程并没有调用wait或waitpid获取子进程的状态信息，那么子进程的进程描述符仍然保存在系统中。这种进程称之为僵死进程。\n",
    "\n",
    "通俗讲就是：\n",
    "\n",
    "**孤儿进程：你爸在你之前死了，你成了孤儿，然后你被进程1收养，你死后的事宜你干爹帮你解决**\n",
    "\n",
    "**僵尸进程：你挂了，你爸忙着干其他事情没有帮你安葬，你变成了孤魂野鬼，你的怨念一直长存世间**\n",
    "\n",
    "举个例子看看：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        time.sleep(1)  # 睡1s\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "    print(\"pid=%d,over\" % os.getpid())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "![孤儿](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725085407754-881176336.png)\n",
    "\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        while True:\n",
    "            print(\"父亲我忙着呢，没时间管你个小屁孩\")\n",
    "            time.sleep(1)\n",
    "\n",
    "    print(\"pid=%d,over\" % os.getpid())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出+测试：\n",
    "![僵尸](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725090628351-1966112474.png)\n",
    "\n",
    "其实僵尸进程的危害真的很大，这也就是为什么有些人为了追求效率过度调用底层，不考虑自己实际情况最后发现还不如用自托管的效率高\n",
    "\n",
    "僵尸进程是杀不死的，必须杀死父类才能彻底解决它们，下面说说怎么让父进程为子进程‘收尸’\n",
    "\n",
    "---\n",
    "\n",
    "### 2.3.父进程回收子进程（wait and waitpid）\n",
    "\n",
    "讲解之前先简单分析一下上面的Linux指令（防止有人不太清楚）\n",
    "\n",
    "**`kill -9 pid`** ==> 以前逆天说过，是无条件杀死进程，其实这种说法不准确，应该是**发信号给某个进程**\n",
    "\n",
    "-9指的就是信号道里面的`SIGKILL`（信号终止），你写成`kill -SIGKILL pid`也一样\n",
    "\n",
    "-9只是系统给的一种简化写法（好像记得1~31信号，各个Linux中都差不多，其他的有点不一样）\n",
    "```shell\n",
    "dnt@MZY-PC:~/桌面/work/PC/python/Thread/Linux kill -l\n",
    " 1) SIGHUP\t 2) SIGINT\t 3) SIGQUIT\t 4) SIGILL\t 5) SIGTRAP\n",
    " 6) SIGABRT\t 7) SIGBUS\t 8) SIGFPE\t 9) SIGKILL\t10) SIGUSR1\n",
    "11) SIGSEGV\t12) SIGUSR2\t13) SIGPIPE\t14) SIGALRM\t15) SIGTERM\n",
    "16) SIGSTKFLT\t17) SIGCHLD\t18) SIGCONT\t19) SIGSTOP\t20) SIGTSTP\n",
    "21) SIGTTIN\t22) SIGTTOU\t23) SIGURG\t24) SIGXCPU\t25) SIGXFSZ\n",
    "26) SIGVTALRM\t27) SIGPROF\t28) SIGWINCH\t29) SIGIO\t30) SIGPWR\n",
    "31) SIGSYS\t34) SIGRTMIN\t35) SIGRTMIN+1\t36) SIGRTMIN+2\t37) SIGRTMIN+3\n",
    "38) SIGRTMIN+4\t39) SIGRTMIN+5\t40) SIGRTMIN+6\t41) SIGRTMIN+7\t42) SIGRTMIN+8\n",
    "43) SIGRTMIN+9\t44) SIGRTMIN+10\t45) SIGRTMIN+11\t46) SIGRTMIN+12\t47) SIGRTMIN+13\n",
    "48) SIGRTMIN+14\t49) SIGRTMIN+15\t50) SIGRTMAX-14\t51) SIGRTMAX-13\t52) SIGRTMAX-12\n",
    "53) SIGRTMAX-11\t54) SIGRTMAX-10\t55) SIGRTMAX-9\t56) SIGRTMAX-8\t57) SIGRTMAX-7\n",
    "58) SIGRTMAX-6\t59) SIGRTMAX-5\t60) SIGRTMAX-4\t61) SIGRTMAX-3\t62) SIGRTMAX-2\n",
    "63) SIGRTMAX-1\t64) SIGRTMAX\t\n",
    "```\n",
    "一般搜索进程中的某个程序一般都是用这个：**`ps -aux | grep xxx`** （`|`其实就是管道，用于有血缘关系进程间通信，等会讲）\n",
    "\n",
    "如果安装了`pstree`就更方便了：**`pstree 13570 -ps`** （Ubuntu自带，CentOS要装下`yum install psmisc`）\n",
    "```py\n",
    "systemd(1)───systemd(1160)───gnome-terminal-(21604)───bash(8169)───python3(13570)───python3(13571)\n",
    "```\n",
    "\n",
    "扩展：**我们平时`Ctrl+C`其实就是给 2）`SIGINT`发一个信号**\n",
    "\n",
    "---\n",
    "\n",
    "#### 2.3.1.wait\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/wait\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/wait</a>\n",
    "\n",
    "步入正题：\n",
    "\n",
    "Python的Wait和C系列的稍有不同，这边重点说说Python：\n",
    "```py\n",
    "help(os.wait)\n",
    "\n",
    "Help on built-in function wait in module posix:\n",
    "\n",
    "wait()\n",
    "    Wait for completion of a child process.\n",
    "    \n",
    "    Returns a tuple of information about the child process:\n",
    "        (pid, status)\n",
    "```\n",
    "`os.wait()`返回一个元组，第一个是进程id，第二个是状态，正常退出是0，被九号信号干死就返回9\n",
    "\n",
    "来个案例：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        wpid, status = os.wait()\n",
    "        print(wpid)\n",
    "        print(status)\n",
    "\n",
    "    print(\"pid=%d,over\" % os.getpid())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "父进程：Pid=22322,PPID=10139\n",
    "子进程：Pid=22323,PPID=22322\n",
    "pid=22323,over\n",
    "22323\n",
    "0\n",
    "pid=22322,over\n",
    "```\n",
    "演示一下被9号信号干死的情况：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        while True:\n",
    "            print(\"孩子老卵，就是不听话\")\n",
    "            time.sleep(1)\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：Pid=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        wpid, status = os.wait()  # 调用一次只能回收一次，想都回收，就来个while循环，-1则退出\n",
    "        print(wpid)\n",
    "        print(status)\n",
    "        if status == 0:\n",
    "            print(\"正常退出\")\n",
    "        elif status == 9:\n",
    "            print(\"被信号9干死了\")\n",
    "\n",
    "    print(\"pid=%d,over\" % os.getpid())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "![回收子进程](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725095801778-1457292536.png)\n",
    "\n",
    "---\n",
    "\n",
    "扩展：（回收所有子进程，status返回-1代表没有子进程了，Python里面没有子进程会触发异常）\n",
    "\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    i = 0\n",
    "    while i < 3:\n",
    "        pid = os.fork()\n",
    "        # 防止产生孙子进程（可以自己思索下）\n",
    "        if pid == 0:\n",
    "            break\n",
    "        i += 1\n",
    "\n",
    "    if i == 0:\n",
    "        print(\"i=%d,子进程：Pid=%d,PPID=%d\" % (i, os.getpid(), os.getppid()))\n",
    "        time.sleep(1)\n",
    "    elif i == 1:\n",
    "        print(\"i=%d,子进程：Pid=%d,PPID=%d\" % (i, os.getpid(), os.getppid()))\n",
    "        time.sleep(1)\n",
    "    elif i == 2:\n",
    "        print(\"i=%d,子进程：Pid=%d,PPID=%d\" % (i, os.getpid(), os.getppid()))\n",
    "        time.sleep(3)\n",
    "        while True:\n",
    "            print(\"(PID=%d)我又老卵了，怎么滴～\" % os.getpid())\n",
    "            time.sleep(3)\n",
    "    elif i==3: # 循环结束后，父进程才会退出，这时候i=3\n",
    "        print(\"i=%d,父进程：Pid=%d,PPID=%d\" % (i, os.getpid(), os.getppid()))\n",
    "        while True:\n",
    "            print(\"等待回收子进程\")\n",
    "            try:\n",
    "                wpid, status = os.wait()\n",
    "                print(wpid)\n",
    "                print(status)\n",
    "                if status == 0:\n",
    "                    print(\"正常退出\")\n",
    "                elif status == 9:\n",
    "                    print(\"被信号9干死了\")\n",
    "            except OSError as ex:\n",
    "                print(ex)\n",
    "                break\n",
    "\n",
    "    print(\"pid=%d,over，ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "演示：看最后一句输出，父进程扫尾工作做完就over了\n",
    "![回收所有子进程](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725105051778-1590933700.png)\n",
    "\n",
    "---\n",
    "\n",
    "#### 2.3.2.waitpid\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/waitpid\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/waitpid</a>\n",
    "\n",
    "上面说的`wait`方法是阻塞进程的一种方式，`waitpid`可以设置不阻塞进程\n",
    "\n",
    "```py\n",
    "help(os.waitpid)\n",
    "\n",
    "Help on built-in function waitpid in module posix:\n",
    "\n",
    "waitpid(pid, options, /)\n",
    "    Wait for completion of a given child process.\n",
    "    \n",
    "    Returns a tuple of information regarding the child process:\n",
    "        (pid, status)\n",
    "    \n",
    "    The options argument is ignored on Windows.\n",
    "```\n",
    "等待进程id为pid的进程结束，返回一个tuple，包括进程的进程ID和退出信息(和os.wait()一样)，参数options会影响该函数的行为。在默认情况下，options的值为0。\n",
    "\n",
    "1. 如果pid是一个正数，waitpid()请求获取一个pid指定的进程的退出信息\n",
    "2. 如果pid为0，则等待并获取当前进程组中的任何子进程的值\n",
    "3. **如果pid为-1，则等待当前进程的任何子进程**\n",
    "4. 如果pid小于-1，则获取进程组id为pid的绝对值的任何一个进程\n",
    "5. 当系统调用返回-1时，抛出一个OSError异常。\n",
    "\n",
    "<a href=\"https://docs.python.org/3/library/os.html#os.waitpid\" target=\"_blank\">官方原话是这样的</a>：（英语好的可以看看我有没有翻译错）\n",
    "```\n",
    "If pid is greater than 0, waitpid() requests status information for that specific process.\n",
    "If pid is 0, the request is for the status of any child in the process group of the current process. \n",
    "If pid is -1, the request pertains to any child of the current process. \n",
    "If pid is less than -1, status is requested for any process in the process group -pid (the absolute value of pid).\n",
    "```\n",
    "\n",
    "options:（宏）\n",
    "```py\n",
    "os.WNOHANG - 如果没有子进程退出，则不阻塞waitpid()调用\n",
    "os.WCONTINUED - 如果子进程从stop状态变为继续执行，则返回进程自前一次报告以来的信息。\n",
    "os.WUNTRACED - 如果子进程被停止过而且其状态信息还没有报告过，则报告子进程的信息。\n",
    "```\n",
    "\n",
    "补充：\n",
    "1. 进程组：每一个进程都属于一个“进程组”，当一个进程被创建的时候，它默认是其父进程所在组的成员（**你们一家**）\n",
    "2. 会  话：几个进程组又构成一个会话（**你们小区**）\n",
    "\n",
    "用法和`wait`差不多，就是多了一个不阻塞线程的方法：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "\n",
    "    if pid == 0:\n",
    "        print(\"[子进程]PID：%d，PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "        time.sleep(2)\n",
    "\n",
    "    elif pid > 0:\n",
    "        print(\"[父进程]PID：%d，PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "        while True:\n",
    "            try:\n",
    "                wpid, status = os.waitpid(-1, os.WNOHANG)\n",
    "                if wpid > 0:\n",
    "                    print(\"回收子进程wpid:%d,状态status:%d\" % (wpid, status))\n",
    "            except OSError:\n",
    "                print(\"没有子进程了\")\n",
    "                break\n",
    "\n",
    "            print(\"父进程忙着挣钱养家呢～\")\n",
    "            time.sleep(3)\n",
    "\n",
    "    print(\"[over]PID：%d，PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[父进程]PID：1371，PPID：29604\n",
    "[子进程]PID：1372，PPID：1371\n",
    "父进程忙着挣钱养家呢～\n",
    "[over]PID：1372，PPID：1371\n",
    "回收子进程wpid:1372,状态status:0\n",
    "父进程忙着挣钱养家呢～\n",
    "没有子进程了\n",
    "[over]PID：1371，PPID：29604\n",
    "```\n",
    "\n",
    "#### 2.3.3.wait3 and wait4\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/blob/master/python/5.concurrent/Linux/wait3.py\" target=\"_blank\">https://github.com/lotapp/BaseCode/blob/master/python/5.concurrent/Linux/wait3.py</a>\n",
    "\n",
    "```py\n",
    "help(os.wait3)\n",
    "\n",
    "Help on built-in function wait3 in module posix:\n",
    "\n",
    "wait3(options)\n",
    "    Wait for completion of a child process.\n",
    "    \n",
    "    Returns a tuple of information about the child process:\n",
    "      (pid, status, rusage)\n",
    "```\n",
    "```py\n",
    "help(os.wait4)\n",
    "\n",
    "Help on built-in function wait4 in module posix:\n",
    "\n",
    "wait4(pid, options)\n",
    "    Wait for completion of a specific child process.\n",
    "    \n",
    "    Returns a tuple of information about the child process:\n",
    "      (pid, status, rusage)\n",
    "```\n",
    "这个是Python扩展的方法，用法和`wait、waitpid`差不多，我就不一个个的举例子了，以`wait3`为例\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "\n",
    "    if pid == 0:\n",
    "        print(\"[子进程]PID：%d，PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "        time.sleep(2)\n",
    "\n",
    "    elif pid > 0:\n",
    "        print(\"[父进程]PID：%d，PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "        while True:\n",
    "            try:\n",
    "                wpid, status, rusage = os.wait3(os.WNOHANG)\n",
    "                if wpid > 0:\n",
    "                    print(\"回收子进程wpid:%d,状态status:%d\\n详细信息：%s\" % (wpid, status,\n",
    "                                                                 rusage))\n",
    "            except OSError:\n",
    "                print(\"没有子进程了\")\n",
    "                break\n",
    "\n",
    "            print(\"父进程忙着挣钱养家呢～\")\n",
    "            time.sleep(3)\n",
    "\n",
    "    print(\"[over]PID：%d，PPID：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出\n",
    "```\n",
    "[父进程]PID：2638，PPID：29604\n",
    "[子进程]PID：2639，PPID：2638\n",
    "父进程忙着挣钱养家呢～\n",
    "[over]PID：2639，PPID：2638\n",
    "回收子进程wpid:2639,状态status:0\n",
    "详细信息：resource.struct_rusage(ru_utime=0.0052179999999999995, ru_stime=0.0052179999999999995, ru_maxrss=7032, ru_ixrss=0, ru_idrss=0, ru_isrss=0, ru_minflt=869, ru_majflt=0, ru_nswap=0, ru_inblock=0, ru_oublock=0, ru_msgsnd=0, ru_msgrcv=0, ru_nsignals=0, ru_nvcsw=2, ru_nivcsw=0)\n",
    "父进程忙着挣钱养家呢～\n",
    "没有子进程了\n",
    "[over]PID：2638，PPID：29604\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 扩展：execl and execlp\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/blob/master/python/5.concurrent/Linux/execl.py\" target=\"_blank\">https://github.com/lotapp/BaseCode/blob/master/python/5.concurrent/Linux/execl.py</a>\n",
    "\n",
    "之前有说fork后，相当于copy了一份，.text里面放的是代码段，如果想要调用另一个程序，可以使用`execlxxx`，他会把.text里面的代码替换掉\n",
    "\n",
    "```py\n",
    "help(os.execl)\n",
    "\n",
    "Help on function execl in module os:\n",
    "\n",
    "execl(file, *args)\n",
    "    execl(file, *args)\n",
    "    \n",
    "    Execute the executable file with argument list args, replacing the\n",
    "    current process.\n",
    "```\n",
    "```py\n",
    "help(os.execlp)\n",
    "\n",
    "Help on function execlp in module os:\n",
    "\n",
    "execlp(file, *args)\n",
    "    execlp(file, *args)\n",
    "    \n",
    "    Execute the executable file (which is searched for along PATH)\n",
    "    with argument list args, replacing the current process.\n",
    "```\n",
    "来看个例子，`os.execl(\"绝对路径\",\"参数或者指令\")` or `os.execlp(\"Path中包含的命令\",\"参数或者指令\")`\n",
    "\n",
    "提示：查看命令路径：eg：`which ls`\n",
    "\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        # 第二个参数不能为None,，第一个路径为绝对路径 eg：os.execl(\"/bin/ls\",\" \")\n",
    "        os.execl(\"/bin/ls\", \"ls\", \"-al\")\n",
    "        # os.execlp(\"ls\", \"ls\", \"-al\")  # 执行Path环境变量可以搜索到的命令\n",
    "        print(\"exec函数族会替换代码，我是不会被执行的，除非上面的出问题了\")\n",
    "\n",
    "    print(\"-\" * 10)  # 父进程执行一次，子进程不会执行\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "注意输出信息：`os.execlp(\"ls\", \"ls\", \"-al\")`\n",
    "```\n",
    "----------\n",
    "总用量 28\n",
    "drwxrwxr-x 6 dnt dnt 4096 7月  26 05:23 .\n",
    "drwxrwxr-x 9 dnt dnt 4096 7月  24 20:55 ..\n",
    "drwxr-xr-x 2 dnt dnt 4096 7月  19 14:47 .ipynb_checkpoints\n",
    "drwxrwxr-x 6 dnt dnt 4096 7月  26 06:27 Linux\n",
    "-rw-rw-r-- 1 dnt dnt   93 7月  26 05:49 temp.py\n",
    "drwxrwxr-x 2 dnt dnt 4096 7月  24 15:29 .vscode\n",
    "drwxrwxr-x 2 dnt dnt 4096 7月  25 12:18 进程\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4.1.进程间通信～文件通信\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/1.file\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/1.file</a>\n",
    "\n",
    "讲管道之前，先说个简单的：通过文件进行通信\n",
    "\n",
    "来一个简单读写的案例先适应下文件操作："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "并发编程～进程先导篇.ipynb\n",
      "从前有座山,山上有座庙,庙里有个老和尚和一个小和尚。有一天,老和尚对小和尚说:\n",
      "test.txt  并发编程～进程先导篇.ipynb\n"
     ]
    }
   ],
   "source": [
    "!ls\n",
    "\n",
    "# 这种写法类似于Net的 using 托管\n",
    "with open(\"test.txt\", \"w\") as f:\n",
    "    f.write(\"从前有座山,山上有座庙,庙里有个老和尚和一个小和尚。有一天,老和尚对小和尚说:\")\n",
    "\n",
    "with open(\"test.txt\", \"r\") as f:\n",
    "    data = f.read()\n",
    "    print(data)\n",
    "\n",
    "!ls"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "来个简单的案例：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "\n",
    "    if pid > 0:\n",
    "        print(\"父进程(pid=%d)开始写入：\" % os.getpid())\n",
    "        with open(str(pid), \"w\") as f:\n",
    "            f.write(\"[父进程写入]从前有座山,山上有座庙,庙里有个老和尚和一个小和尚。有一天,老和尚对小和尚说:\\n\")\n",
    "        time.sleep(2)\n",
    "        print(\"父进程(pid=%d)开始读取：\" % os.getpid())\n",
    "        with open(str(pid), \"r\") as f:\n",
    "            print(f.read())\n",
    "\n",
    "        wpid, status = os.wait()  # 收尸\n",
    "        print(\"pid=%d已经回收,status:%d\" % (wpid, status))\n",
    "\n",
    "    elif pid == 0:\n",
    "        print(\"子进程(pid=%d)开始读取：\" % os.getpid())\n",
    "        with open(str(os.getpid()), \"r\") as f:\n",
    "            print(f.read())\n",
    "        print(\"子进程(pid=%d)开始追加：\" % os.getpid())\n",
    "        with open(str(os.getpid()), \"a\") as f:  # 追加\n",
    "            f.write(\"[子进程追加]从前有座山,山上有座庙,庙里有个老和尚和一个小和尚。有一天,老和尚对小和尚说:\\n\")\n",
    "\n",
    "    print(\"\\n进程(pid=%d)完蛋了\" % os.getpid())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "\n",
    "```\n",
    "图示：\n",
    "![文件通信](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725143008836-793493048.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4.2.进程间通信～队列 Queue（常用）\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/2.Queue\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/2.Queue</a>\n",
    "\n",
    "```py\n",
    "from multiprocessing import Queue\n",
    "\n",
    "help(Queue)\n",
    "\n",
    "Help on method Queue in module multiprocessing.context:\n",
    "\n",
    "Queue(maxsize=0) method of multiprocessing.context.DefaultContext instance\n",
    "    Returns a queue object\n",
    "```\n",
    "实例化对象帮助文档：\n",
    "```py\n",
    "from multiprocessing import Queue\n",
    "\n",
    "q = Queue(2)\n",
    "help(q)\n",
    "\n",
    "Help on Queue in module multiprocessing.queues object:\n",
    "\n",
    "class Queue(builtins.object)\n",
    " |  Methods defined here:\n",
    " |  \n",
    " |  __getstate__(self)\n",
    " |  \n",
    " |  __init__(self, maxsize=0, *, ctx)\n",
    " |      Initialize self.  See help(type(self)) for accurate signature.\n",
    " |  \n",
    " |  __setstate__(self, state)\n",
    " |  \n",
    " |  cancel_join_thread(self)\n",
    " |  \n",
    " |  close(self)\n",
    " |  \n",
    " |  empty(self)\n",
    " |  \n",
    " |  full(self)\n",
    " |  \n",
    " |  get(self, block=True, timeout=None)\n",
    " |  \n",
    " |  get_nowait(self)\n",
    " |  \n",
    " |  join_thread(self)\n",
    " |  \n",
    " |  put(self, obj, block=True, timeout=None)\n",
    " |  \n",
    " |  put_nowait(self, obj)\n",
    " |  \n",
    " |  qsize(self)\n",
    " |  \n",
    " |  ----------------------------------------------------------------------\n",
    " |  Data descriptors defined here:\n",
    " |  \n",
    " |  __dict__\n",
    " |      dictionary for instance variables (if defined)\n",
    " |  \n",
    " |  __weakref__\n",
    " |      list of weak references to the object (if defined)\n",
    "```\n",
    "详细内容（如：非阻塞、池中应用等）下次讲代码的时候会详说，简单看个例子：\n",
    "\n",
    "```py\n",
    "import os\n",
    "from multiprocessing import Queue\n",
    "\n",
    "def main():\n",
    "    q = Queue(1)  # 创建一个容量为1的队列（只能put接受1条,get取出后才可以放）\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"[子进程]:pid:%d,ppid:%d\" % (os.getpid(), os.getppid()))\n",
    "        q.put(\"父亲大人，我可以出去玩吗？\")\n",
    "        output = q.get()\n",
    "        print(\"[子进程]收到父亲大人回复：%s\" % output)\n",
    "    elif pid > 0:\n",
    "        print(\"[父进程]:pid:%d,ppid:%d\" % (os.getppid(), os.getppid()))\n",
    "        output = q.get()  # 儿子每天出去都会说，等待ing\n",
    "        print(\"[父进程]收到儿子的话：%s\" % output)\n",
    "        q.put(\"准了\")\n",
    "\n",
    "        wpid, status = os.wait()\n",
    "        print(\"[父进程]帮pid:%d收尸，状态：%d\" % (wpid, status))\n",
    "\n",
    "    print(\"[OVER]:pid:%d,ppid:%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出:\n",
    "```\n",
    "[父进程]:pid:12403,ppid:12403\n",
    "[子进程]:pid:744,ppid:743\n",
    "[父进程]收到儿子的话：父亲大人，我可以出去玩吗？\n",
    "[子进程]收到父亲大人回复：准了\n",
    "[OVER]:pid:744,ppid:743\n",
    "[父进程]帮pid:744收尸，状态：0\n",
    "[OVER]:pid:743,ppid:12403\n",
    "```\n",
    "\n",
    "### 2.4.3.进程间通信～PIPE匿名管道（常用）\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/3.pipe\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/3.pipe</a>\n",
    "\n",
    "知识普及：\n",
    "1. 命令模式下默认有六个终端tty1-tty6\n",
    "2. tty7代表图形登录\n",
    "3. 远程登录会显示pts/0,1,2...\n",
    "\n",
    "如果终端的概念还不清楚可以看之前的文章：<a href=\"https://www.cnblogs.com/dunitian/p/6658273.html\" target=\"_blank\">https://www.cnblogs.com/dunitian/p/6658273.html</a>\n",
    "\n",
    "```py\n",
    "help(os.pipe)\n",
    "\n",
    "Help on built-in function pipe in module posix:\n",
    "\n",
    "pipe()\n",
    "    Create a pipe.\n",
    "    \n",
    "    Returns a tuple of two file descriptors:\n",
    "      (read_fd, write_fd)\n",
    "```\n",
    "匿名管道的模式其实我们平时都在用，只是不知道而已，比如：**`ps aux | grep \"python\"`** 这个 **`|`** 就是匿名管道\n",
    "\n",
    "**本质**：内核的缓冲区，不占用磁盘空间（可以看成伪文件）【默认4k，相差不大的情况下系统会自动微调大小】\n",
    "\n",
    "我们来看一下：**`ulimit -a`**\n",
    "\n",
    "Ubuntu 18.04\n",
    "```\n",
    "core file size          (blocks, -c) 0\n",
    "data seg size           (kbytes, -d) unlimited\n",
    "scheduling priority             (-e) 0\n",
    "file size               (blocks, -f) unlimited\n",
    "pending signals                 (-i) 14894\n",
    "max locked memory       (kbytes, -l) 16384\n",
    "max memory size         (kbytes, -m) unlimited\n",
    "open files                      (-n) 1024\n",
    "pipe size            (512 bytes, -p) 8\n",
    "POSIX message queues     (bytes, -q) 819200\n",
    "real-time priority              (-r) 0\n",
    "stack size              (kbytes, -s) 8192\n",
    "cpu time               (seconds, -t) unlimited\n",
    "max user processes              (-u) 14894\n",
    "virtual memory          (kbytes, -v) unlimited\n",
    "file locks                      (-x) unlimited\n",
    "```\n",
    "CentOS 7.5\n",
    "```\n",
    "core file size          (blocks, -c) 0\n",
    "data seg size           (kbytes, -d) unlimited\n",
    "scheduling priority             (-e) 0\n",
    "file size               (blocks, -f) unlimited\n",
    "pending signals                 (-i) 3543\n",
    "max locked memory       (kbytes, -l) 64\n",
    "max memory size         (kbytes, -m) unlimited\n",
    "open files                      (-n) 1024\n",
    "pipe size            (512 bytes, -p) 8\n",
    "POSIX message queues     (bytes, -q) 819200\n",
    "real-time priority              (-r) 0\n",
    "stack size              (kbytes, -s) 8192\n",
    "cpu time               (seconds, -t) unlimited\n",
    "max user processes              (-u) 3543\n",
    "virtual memory          (kbytes, -v) unlimited\n",
    "file locks                      (-x) unlimited\n",
    "```\n",
    "![Ubuntu2](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726115930295-1982350109.png)\n",
    "![CentOS2](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726115958566-2082980129.png)\n",
    "\n",
    "**原理**：算法实现的环形**队列**（队列：先进先出）\n",
    "\n",
    "**特点**：\n",
    "1. 操作管道的进程被销毁后，管道自动被释放\n",
    "2. 管道默认是阻塞（读、写两端都阻塞）\n",
    "3. 管道有两个端，一个是读端（read_fd，一般都为3),一个是写端（write_fd，一般都为4）\n",
    "4. **单向传输**\n",
    "\n",
    "4的意思是这样的（网上找个图，然后改造一下）\n",
    "![1.网络](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726133938904-335895135.png)\n",
    "\n",
    "验证一下3：\n",
    "![4.fdTuple](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725210758567-1020174395.png)\n",
    "\n",
    "为什么是3开始呢？查看一下源码：（<a href=\"https://github.com/python/cpython/blob/v3.7.0/Lib/pty.py\" target=\"_blank\">https://github.com/python/cpython/blob/v3.7.0/Lib/pty.py</a>）\n",
    "```py\n",
    "STDIN_FILENO = 0  # 看这：文件描述符输入（读端）\n",
    "STDOUT_FILENO = 1 # 看这：文件描述符输出（写端）\n",
    "STDERR_FILENO = 2 # 已经被占用了0~2了，自然从3开始\n",
    "\n",
    "# 下面的不用你会，上面Code看完，我们的目的就达到了，下面看看即可\n",
    "def fork():\n",
    "    \"\"\"fork() -> (pid, master_fd) Fork分叉后让子进程成为控制终端的会话领导者\"\"\"\n",
    "    try:\n",
    "        pid, fd = os.forkpty() # 设置会话领导\n",
    "    except (AttributeError, OSError):\n",
    "        pass\n",
    "    else: # 没有错误执行\n",
    "        if pid == CHILD:\n",
    "            os.setsid()\n",
    "        return pid, fd\n",
    "\n",
    "    master_fd, slave_fd = openpty()\n",
    "    pid = os.fork()\n",
    "    if pid == CHILD:\n",
    "        # 建立一个新的会话\n",
    "        os.setsid()\n",
    "        os.close(master_fd)\n",
    "\n",
    "        # 把子进程里面的 slave_fd 重定向到 stdin/stdout/stderr\n",
    "        os.dup2(slave_fd, STDIN_FILENO)\n",
    "        os.dup2(slave_fd, STDOUT_FILENO)\n",
    "        os.dup2(slave_fd, STDERR_FILENO)\n",
    "        if (slave_fd > STDERR_FILENO):\n",
    "            os.close (slave_fd)\n",
    "\n",
    "        # 显式打开tty，使它成为一个tty控制\n",
    "        tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)\n",
    "        os.close(tmp_fd)\n",
    "    else:\n",
    "        os.close(slave_fd)\n",
    "\n",
    "    # Parent and child process.\n",
    "    return pid, master_fd\n",
    "```\n",
    "\n",
    "画个大纲图理解一下：（读的时候关闭写，写的时候关闭读）\n",
    "![父子进程图示](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726080550736-577227086.png)\n",
    "\n",
    "结合单向传输理解一下：（父子只能一个人写，另一个人只能读）\n",
    "![PIPE](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180725205347455-1105690210.png)\n",
    "简单概况上图：**子进程只读，父进程只写** or **子进程只写，父进程只读** (如果想要相互读写通信～两根管道走起)\n",
    "\n",
    "简单分析一下 **`ps aux | grep python`** ，本来ps aux是准备在终端中输出的，现在写入内核缓冲区了，grep从内核缓冲区里面读取，把符合条件的输出到终端\n",
    "\n",
    "终端文件描述获取：\n",
    "```py\n",
    "import sys\n",
    "\n",
    "sys.stdin.fileno() # STDIN_FILENO = 0：文件描述符输入（读端）\n",
    "sys.stdout.fileno() # STDOUT_FILENO = 1：看这：文件描述符输出（写端）\n",
    "```\n",
    "\n",
    "我们用程序实现一个同样效果的：(`grep`有颜色，其实就是加了`--color=auto`)\n",
    "```py\n",
    "import os\n",
    "import sys\n",
    "\n",
    "def main():\n",
    "    # 创建内核缓存区（伪文件）\n",
    "    read_fd, write_fd = os.pipe()\n",
    "    print(\"read_fd:%s\\nwrite_fd:%s\" % (read_fd, write_fd))\n",
    "\n",
    "    pid = os.fork()\n",
    "    if pid > 0:\n",
    "        print(\"[父进程]pid=%d,ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        # 写或者读，则需要关闭另一端（防止自己写自己读）\n",
    "        os.close(read_fd)\n",
    "        # dup2(oldfd,newfd) 把写端数据重定向到文件描述符输出端\n",
    "        os.dup2(write_fd, sys.stdout.fileno())  # STDOUT_FILENO==1 (文件描述符输出，写端)\n",
    "        # 僵桃李代\n",
    "        os.execlp(\"ps\", \"ps\", \"aux\")\n",
    "\n",
    "    elif pid == 0:\n",
    "        print(\"[子进程]pid=%d,ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        # 子进程现在需要读，关闭写段\n",
    "        os.close(write_fd)\n",
    "        # dup2(oldfd,newfd) 把读端数据重定向到文件描述符输入端\n",
    "        os.dup2(read_fd, sys.stdin.fileno())  # STDOUT_FILENO == 0 (文件描述符输入，读端)\n",
    "        # 僵桃李代 （默认是从终端读，重定向后从内核缓冲区读）\n",
    "        os.execlp(\"grep\", \"grep\", \"python\", \"--color=auto\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（用到的函数：`os.pipe()` and `os.dup2(oldfd,newfd)`）\n",
    "![匿名管道](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726063848069-655266438.png)\n",
    "\n",
    "PS：在C系列里面如果你该关闭的fd没关，会资源浪费，python好像做了处理，没能够问题复现，所以还是建议**父子一方只读，一方只写**\n",
    "\n",
    "---\n",
    "\n",
    "概念再理解：fork了两个子进程，则文件描述符被复制了2份，大家文件描述符的3、4都指向了`pipe管道`的`read_fd`和`write_fd`\n",
    "![子进程通信1]](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726093144117-1244358084.png)\n",
    "\n",
    "来张图理解一下，哪些fd被close了(如果让子进程之间通信，父进程因为不读不写，所以读写都得关闭)\n",
    "![子进程通信2](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726093150955-1505869480.png)\n",
    "代码演示：（这次注释很全）\n",
    "```py\n",
    "import os\n",
    "import sys\n",
    "import time\n",
    "\n",
    "def main():\n",
    "\n",
    "    read_fd, write_fd = os.pipe()  # 可以思考为啥在上面创建管道（提示.text代码段都一样）\n",
    "\n",
    "    i = 0\n",
    "    while i < 2:\n",
    "        pid = os.fork()\n",
    "        # 防止子进程生猴子\n",
    "        if pid == 0:\n",
    "            break\n",
    "        i += 1\n",
    "\n",
    "    # 子进程1\n",
    "    if i == 0:\n",
    "        print(\"[子进程%d]pid=%d，ppid=%d\" % (i, os.getpid(), os.getppid()))\n",
    "\n",
    "        # 准备重定向到写端，所以先关了读端\n",
    "        os.close(read_fd)\n",
    "        os.dup2(write_fd, sys.stdout.fileno())  # STDOUT_FILENO == 1 (文件描述符输出，写端)\n",
    "\n",
    "        # 僵桃李代\n",
    "        os.execlp(\"ps\", \"ps\", \"-aux\")\n",
    "        # 僵桃李代后，.text代码段都被替换了，自然不会执行\n",
    "        print(\"我是不会执行的，不信你看呗\")\n",
    "    elif i == 1:\n",
    "        print(\"[子进程%d]pid=%d，ppid=%d\" % (i, os.getpid(), os.getppid()))\n",
    "\n",
    "        # 准备重定向到读端，所以先关了写端\n",
    "        os.close(write_fd)\n",
    "        os.dup2(read_fd, sys.stdin.fileno())  # STDIN_FILENO == 0 (文件描述符输入，读端)\n",
    "\n",
    "        # 僵桃李代  ”bash“是查找关键词，你写你想找的字符串即可\n",
    "        os.execlp(\"grep\", \"grep\", \"bash\", \"--color=auto\")\n",
    "\n",
    "        # 僵桃李代后，.text代码段都被替换了，自然不会执行\n",
    "        print(\"我是不会执行的，不信你看呗\")\n",
    "    elif i == 2:\n",
    "        print(\"[父进程]pid=%d，ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        # 我不写不读\n",
    "        os.close(read_fd)\n",
    "        os.close(write_fd)\n",
    "\n",
    "        # 为了大家熟练掌握wait系列，这次用waitpid\n",
    "        while (True):\n",
    "            info = ()\n",
    "            try:\n",
    "                info = os.waitpid(-1, os.WNOHANG)  # 非阻塞的方式回收所有子进程\n",
    "            except OSError:\n",
    "                break  # waitpid返回-1的时候，Python会抛出异常\n",
    "\n",
    "            if info[0] > 0:\n",
    "                print(\"父进程收尸成功：pid=%d，ppid=%d，状态status：%d\" %\n",
    "                      (os.getpid(), os.getppid(), info[1]))\n",
    "            print(\"父进程做其他事情...\")\n",
    "            time.sleep(0.005)  # 休息 0.005s\n",
    "\n",
    "    print(\"[父进程-遗言]pid=%d，ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "结果：\n",
    "```\n",
    "[父进程]pid=18678，ppid=27202\n",
    "[子进程0]pid=18679，ppid=18678\n",
    "[子进程1]pid=18680，ppid=18678\n",
    "父进程做其他事情...\n",
    "父进程做其他事情...\n",
    "父进程做其他事情...\n",
    "父进程做其他事情...\n",
    "dnt       4622  0.0  0.1  24880  5688 pts/2    Ss   05:28   0:00 bash\n",
    "父进程做其他事情...\n",
    "dnt      15419  0.0  0.1  25152  5884 pts/0    Ss+  06:29   0:00 /bin/bash\n",
    "dnt      18680  0.0  0.0  16184  1044 pts/4    S+   13:25   0:00 grep bash --color=auto\n",
    "dnt      27202  0.0  0.1  25012  6052 pts/4    Ss   08:25   0:00 bash\n",
    "父进程收尸成功：pid=18678，ppid=27202，状态status：0\n",
    "父进程做其他事情...\n",
    "父进程收尸成功：pid=18678，ppid=27202，状态status：0\n",
    "父进程做其他事情...\n",
    "[父进程-遗言]pid=18678，ppid=27202\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'\\xe5\\xb0\\xb4\\xe5\\xb0\\xac'\n",
      "尴尬\n"
     ]
    }
   ],
   "source": [
    "# 说管道读写之前，先复习个知识点：\n",
    "bts = \"尴尬\".encode()\n",
    "b_str = bts.decode()\n",
    "print(bts)\n",
    "print(b_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 匿名管道读写操作\n",
    "\n",
    "上面知识点忘了可以复习一下：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html#1.2.字符串和编码\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9278573.html#1.2.字符串和编码</a>\n",
    "\n",
    "用到的函数：（这个就不需要使用`dup2`来重定向到终端了【有血缘关系的进程之间通信，并不依赖于终端显示】）\n",
    "\n",
    "`os.write(fd, str)`写入字符串到文件描述符 fd中. 返回实际写入的字符串长度\n",
    "\n",
    "`os.read(fd, n)`从文件描述符 fd 中读取最多 n 个字节，返回包含读取字节的字符串\n",
    "\n",
    "如果文件描述符fd对应文件已达到结尾, 返回一个空字符串\n",
    "\n",
    "举个父子间通信的例子（比C系列简单太多）【下次讲的通用Code会更简单】\n",
    "```py\n",
    "import os\n",
    "\n",
    "def close_fd(*fd_tuple_args):\n",
    "    \"\"\"关闭fd，fd_tuple_args是可变参数\"\"\"\n",
    "    for item in fd_tuple_args:\n",
    "        os.close(item[0])\n",
    "        os.close(item[1])\n",
    "\n",
    "def main():\n",
    "    # 管道是单向的，相互读写，那就创建两个管道\n",
    "    fd_tuple1 = os.pipe()  # 进程1写，进程2读\n",
    "    fd_tuple2 = os.pipe()  # 进程2写，进程1读\n",
    "\n",
    "    i = 0\n",
    "    while (i < 2):\n",
    "        pid = os.fork()\n",
    "        if pid == 0:\n",
    "            break\n",
    "        i += 1\n",
    "    # 子进程1\n",
    "    if i == 0:\n",
    "        print(\"[子进程]pid：%d，ppid：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        os.close(fd_tuple1[0])  # 进程1写，则关闭下读端\n",
    "        msg_str = \"进程1说：兄弟，今天撸串吗？\"\n",
    "        os.write(fd_tuple1[1], msg_str.encode())  # 把字符串xxx转换成bytes\n",
    "\n",
    "        # 不读的我关闭掉：\n",
    "        os.close(fd_tuple2[1])  # 进程2写，我不需要写，关闭写端\n",
    "        bts = os.read(fd_tuple2[0], 1024)\n",
    "        print(\"[子进程1]\", bts.decode())\n",
    "\n",
    "        exit(0)  # 退出后就不执行下面代码块语句了\n",
    "    # 子进程2\n",
    "    elif i == 1:\n",
    "        print(\"[子进程2]pid：%d，ppid：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        os.close(fd_tuple1[1])  # 进程2读，则关闭下写端\n",
    "        bts = os.read(fd_tuple1[0], 1024)\n",
    "        print(\"[子进程2]\", bts.decode())\n",
    "\n",
    "        # 不读的我关闭掉：\n",
    "        os.close(fd_tuple2[0])  # 进程2写，关闭读端\n",
    "        msg_str = \"进程2说：可以可以～\"\n",
    "        os.write(fd_tuple2[1], msg_str.encode())  # 把字符串xxx转换成bytes\n",
    "\n",
    "        exit()  # 不加参数默认是None\n",
    "    # 父进程\n",
    "    elif i == 2:\n",
    "        print(\"[父进程]pid：%d，ppid：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        # 父进程不读不写，就看看\n",
    "        close_fd(fd_tuple1, fd_tuple2)\n",
    "\n",
    "        # 收尸ing\n",
    "        while True:\n",
    "            try:\n",
    "                wpid, status = os.wait()\n",
    "                print(\"[父进程～收尸]子进程PID：%d 的状态status：%d\" % (wpid, status))\n",
    "            except OSError:\n",
    "                break\n",
    "    # 子进程都exit()退出了，不会执行这句话了\n",
    "    print(\"[父进程遗言]pid：%d,ppid：%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出结果：\n",
    "```\n",
    "[父进程]pid：12002，ppid：27202\n",
    "[子进程2]pid：12004，ppid：12002\n",
    "[子进程]pid：12003，ppid：12002\n",
    "[子进程2] 进程1说：兄弟，今天撸串吗？\n",
    "[子进程1] 进程2说：可以可以～\n",
    "[父进程～收尸]子进程PID：12003 的状态status：0\n",
    "[父进程～收尸]子进程PID：12004 的状态status：0\n",
    "[父进程遗言]pid：12002,ppid：27202\n",
    "```\n",
    "\n",
    "#### 非阻塞管道（简写法）\n",
    "\n",
    "队列的`get`，`put`方法默认也是阻塞的，如果想非阻塞可以调用`get_nowait`和`put_nowait`来变成非阻塞，那pipe管道呢？\n",
    "\n",
    "C系列一般使用`fcntl`来实现，Python进行了封装，我们可以通过`os.pipe2(os.O_NONBLOCK)`来设置非阻塞管道\n",
    "```\n",
    "help(os.pipe2)\n",
    "\n",
    "Help on built-in function pipe2 in module posix:\n",
    "\n",
    "pipe2(flags, /)\n",
    "    Create a pipe with flags set atomically.\n",
    "\n",
    "    Returns a tuple of two file descriptors:\n",
    "      (read_fd, write_fd)\n",
    "\n",
    "    flags can be constructed by ORing together one or more of these values:\n",
    "    O_NONBLOCK, O_CLOEXEC.\n",
    "```\n",
    "举个例子：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    r_fd, w_fd = os.pipe2(os.O_NONBLOCK | os.O_CLOEXEC)\n",
    "\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：pid=%d，ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "        time.sleep(0.5)\n",
    "\n",
    "        # 和父进程进行通信\n",
    "        os.close(r_fd)\n",
    "        os.write(w_fd, \"老爸，我出去玩了～\".encode())\n",
    "\n",
    "        exit(0)  # 子进程退出\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：pid=%d，ppid=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        # 读儿子的留言\n",
    "        os.close(w_fd)\n",
    "        b_msg = b\"\"\n",
    "        while True:\n",
    "            try:\n",
    "                b_msg = os.read(r_fd, 1)  # 没有数据就出错（一般都是等待一会，也可以和信号联合使用）\n",
    "            except OSError:\n",
    "                print(\"儿子怎么没有留言呢？\")\n",
    "\n",
    "            print(\"父进程：做其他事情...\")\n",
    "            if len(b_msg) > 0:\n",
    "                break\n",
    "            time.sleep(0.1)\n",
    "\n",
    "        # 继续读剩下的消息\n",
    "        b_msg += os.read(r_fd, 1024)\n",
    "        print(\"儿子留言:\", b_msg.decode())\n",
    "\n",
    "        wpid, status = os.wait()\n",
    "        print(\"帮儿子做扫尾工作：pid=%d，status=%d\" % (wpid, status))\n",
    "\n",
    "    print(\"父进程遗言：pid=%d，status=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "父进程：pid=31430，ppid=27202\n",
    "子进程：pid=31431，ppid=31430\n",
    "儿子怎么没有留言呢？\n",
    "父进程：做其他事情...\n",
    "儿子怎么没有留言呢？\n",
    "父进程：做其他事情...\n",
    "儿子怎么没有留言呢？\n",
    "父进程：做其他事情...\n",
    "儿子怎么没有留言呢？\n",
    "父进程：做其他事情...\n",
    "儿子怎么没有留言呢？\n",
    "父进程：做其他事情...\n",
    "父进程：做其他事情...\n",
    "儿子留言: 老爸，我出去玩了～\n",
    "帮儿子做扫尾工作：pid=31431，status=0\n",
    "父进程遗言：pid=31430，status=27202\n",
    "```\n",
    "\n",
    "扩展：\n",
    "1. 数据只能读1次（队列和栈都这样）\n",
    "2. 匿名管道必须有血缘关系的进程才能通信\n",
    "3. <a href=\"https://baike.baidu.com/item/半双工通信\" target=\"_blank\">半双工通信</a>：同一时刻里，信息只能有一个传输方向（类似于对讲机）\n",
    "    - <a href=\"https://baike.baidu.com/item/单工通信\" target=\"_blank\">单工通信</a>：消息只能单方向传输（类似于遥控器）\n",
    "    - <a href=\"https://baike.baidu.com/item/半双工通信\" target=\"_blank\">半双工通信</a>：类似于对讲机\n",
    "    - <a href=\"https://baike.baidu.com/item/双工通信\" target=\"_blank\">双工通信</a>：类似于电话\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4.4.进程间通信～FIFO有名管道\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/4.fifo\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/4.fifo</a>\n",
    "\n",
    "**<a href=\"https://baike.baidu.com/item/FIFO管道\" target=\"_blank\">FIFO管道</a>**：\n",
    "\n",
    "1. 有名管道，除了血缘关系进程通信，没有血缘关系的进程也可以通信\n",
    "2. 在磁盘上有会存放一个文件类型为`p`，大小为`0`的管道文件（伪文件，大小始终为0）\n",
    "3. 内核中有一个对应的缓冲区（数据就放在里面）\n",
    "4. 半双工通信：同一时刻里，信息只能有一个传输方向（类似于对讲机）\n",
    "5. fifo要求读写双方必须同时打开才可以继续进行读写操作，否则打开操作会堵塞直到对方也打开\n",
    "6. 如果读端全部关闭，管道破裂，进程自动被终止（PIPE也是这样的）\n",
    "\n",
    "对2的验证：\n",
    "其实你用`ll`来查看，就是文件类型为`p`的文件（大小始终为0）\n",
    "![5.mkfifo](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726181246881-1377165632.png)\n",
    "\n",
    "Linux底层提供了`mkfifo`函数，Python创建使用**`os.mkfifo()`**\n",
    "\n",
    "画个图来看3：\n",
    "![5.fifo图示](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180726200937621-700677810.png)\n",
    "\n",
    "**知识普及**：\n",
    "```py\n",
    "help(os.open)\n",
    "\n",
    "Help on built-in function open in module posix:\n",
    "\n",
    "open(path, flags, mode=511, *, dir_fd=None)\n",
    "    Open a file for low level IO.  Returns a file descriptor (integer).\n",
    "    \n",
    "    If dir_fd is not None, it should be a file descriptor open to a directory,\n",
    "      and path should be relative; path will then be relative to that directory.\n",
    "    dir_fd may not be implemented on your platform.\n",
    "      If it is unavailable, using it will raise a NotImplementedError.\n",
    "```\n",
    "\n",
    "`flags` -- 该参数可以是以下选项，多个使用 `|` 隔开：\n",
    "- **os.O_RDONLY: 以只读的方式打开**\n",
    "- **os.O_WRONLY: 以只写的方式打开**\n",
    "- **os.O_RDWR : 以读写的方式打开**\n",
    "- **os.O_NONBLOCK: 打开时不阻塞**\n",
    "- **os.O_APPEND: 以追加的方式打开**\n",
    "- os.O_CREAT: 创建并打开一个新文件\n",
    "- os.O_TRUNC: 打开一个文件并截断它的长度为零（必须有写权限）\n",
    "- os.O_EXCL: 如果指定的文件存在，返回错误\n",
    "- os.O_SHLOCK: 自动获取共享锁\n",
    "- os.O_EXLOCK: 自动获取独立锁\n",
    "- os.O_DIRECT: 消除或减少缓存效果\n",
    "- os.O_FSYNC : 同步写入\n",
    "- os.O_NOFOLLOW: 不追踪软链接\n",
    "\n",
    "---\n",
    "\n",
    "很多人直接使用了Open方法`open(fifo_path, \"r\")`和`open(fifo_path, \"w\")`貌似也是可以的，但是不推荐\n",
    "\n",
    "我们使用<a href=\"https://docs.python.org/3/library/functions.html?highlight=open#open\" target=\"_blank\">官方推荐的方法</a>：\n",
    "\n",
    "#### 无血缘关系通信\n",
    "\n",
    "fifo操作非常简单，和文件IO操作几乎一样，看个**无血缘关系进程通信**的例子：\n",
    "\n",
    "进程1源码：r_fifo.py\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    file_name = \"fifo_file\"\n",
    "    if not os.path.exists(file_name):\n",
    "        os.mkfifo(file_name)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDONLY)  # 只读（阻塞）\n",
    "    while True:\n",
    "        b_msg = os.read(fd, 1024)\n",
    "        if len(b_msg) > 0:\n",
    "            print(b_msg.decode())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "进程2源码：w_fifo.py\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    file_name = \"fifo_file\"\n",
    "    if not os.path.exists(file_name):\n",
    "        os.mkfifo(file_name)\n",
    "\n",
    "    fd = os.open(file_name, os.O_WRONLY)  # 只写\n",
    "    while True:\n",
    "        time.sleep(1)  # 模拟一下实际生产环境下的 读快写慢\n",
    "        try:\n",
    "            os.write(fd, \"我是说话有魔性，喝水会长胖的小明同学\".encode())  # 写入bytes\n",
    "        except BrokenPipeError:\n",
    "            print(\"如果读端全部关闭，管道破裂，进程自动被终止\")\n",
    "            break\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "做个读端的测试：\n",
    "![fifo小明](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180727173356717-141783716.gif)\n",
    "\n",
    "读写双测：（fifo文件大小始终为0，只是伪文件而已）\n",
    "![fifo小明2](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180727173409420-1381699629.gif)\n",
    "\n",
    "扩展一下，如果你通过终端读写呢？（同上）\n",
    "![fifotest](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180727173423973-1909386693.gif)\n",
    "\n",
    "**再来个读写的案例**\n",
    "\n",
    "3.rw_fifo1.py\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    file_name = \"fifo_temp\"\n",
    "    if not os.path.exists(file_name):\n",
    "        os.mkfifo(file_name)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDWR)  # 你输入os.O_rw就会有这个选项了，不用硬记\n",
    "    msg = os.read(fd, 1024).decode()  # 阻塞的方式，不用担心\n",
    "    print(\"[进程2]%s\" % msg)\n",
    "    os.write(fd, \"小明啊，你忘记你长几斤肉了?\".encode())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "rw_fifo2.py\n",
    "```\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    file_name = \"fifo_temp\"\n",
    "    if not os.path.exists(file_name):\n",
    "        os.mkfifo(file_name)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDWR)  # 你输入os.O_rw就会有这个选项了，不用硬记\n",
    "    os.write(fd, \"小潘，撸串去不?\".encode())\n",
    "\n",
    "    time.sleep(3)  # 防止自己写的被自己读了\n",
    "\n",
    "    msg = os.read(fd, 1024).decode()  # 阻塞的方式，不用担心\n",
    "    print(\"[进程1]]%s\" % msg)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "![5.fiforw](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180727203817607-528111064.gif)\n",
    "\n",
    "#### 有血缘关系通信\n",
    "\n",
    "来个父子间通信：（代码比较简单，和上面差不多，看看即可）\n",
    "```py\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    file_name = \"fifo_test\"\n",
    "    if not os.path.exists(file_name):\n",
    "        os.mkfifo(file_name)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDWR)  # 读写方式打开文件描述符 （O_RDONLY | O_WRONLY）\n",
    "\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"子进程：PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        os.write(fd, \"子进程说：老爸，我想出去玩\".encode())  # 写\n",
    "        msg = os.read(fd, 1024).decode()  # 读\n",
    "        print(\"[子进程]%s\" % msg)\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "        msg = os.read(fd, 1024).decode()  # 阻塞方式，不用担心\n",
    "        print(\"[父进程]%s\" % msg)\n",
    "        os.write(fd, \"父进程说：去吧乖儿子\".encode())\n",
    "\n",
    "        # 给子进程收尸\n",
    "        wpid, status = os.wait()\n",
    "        print(\"父进程收尸：子进程PID=%d，PPID=%d\" % (wpid, status))\n",
    "\n",
    "    print(\"进程遗言：PID=%d，PPID=%d\" % (os.getpid(), os.getppid()))  # 剩下的代码段\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "父进程：PID:21498，PPID:20943\n",
    "子进程：PID:21499，PPID:21498\n",
    "[父进程]子进程说：老爸，我想出去玩\n",
    "[子进程]父进程说：去吧乖儿子\n",
    "进程遗言：PID=21499，PPID=21498\n",
    "父进程收尸：子进程PID=21499，PPID=0\n",
    "进程遗言：PID=21498，PPID=20943\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4.5.进程间通信～MMAP内存映射（常用）\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/5.mmap\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/5.mmap</a>\n",
    "\n",
    "好处：内存操作，比IO快\n",
    "\n",
    "缺点：和文件一样不会像管道一样阻塞（读的可能不全，需要自己考虑读写效率）\n",
    "\n",
    "画个简单的图示：\n",
    "![1.mmap图示](https://images2018.cnblogs.com/blog/658978/201807/658978-20180728113442832-944980390.png)\n",
    "PS：**内存映射一个文件并不会导致整个文件被读取到内存中**:\n",
    "1. 文件并没有被复制到内存缓存中，操作系统仅仅为文件内容保留了一段虚拟内存。\n",
    "2. 当你访问文件的不同区域时，这些区域的内容才根据需要被读取并映射到内存区域中。\n",
    "3. 没有访问的部分还是留在磁盘上\n",
    "\n",
    "以Linux为例，简单解析一下帮助文档：（加粗的是必填参数）\n",
    "```py\n",
    "mmap.mmap（fileno,length[,flags=MAP_SHARED][,prot=PROT_WRITE|PROT_READ][,access=ACCESS_DEFAULT][,offset]）\n",
    "```\n",
    "1. **fileno**：就是我们经常说的`文件描述fd`\n",
    "    1. 可以通过`os.open()`直接打开fd\n",
    "    2. 也可以调用文件的`f.fileno()`\n",
    "2. **length**：映射区大小，（一般写0就OK了）\n",
    "    1. 如果length为0，则映射的最大长度将是调用时文件的当前大小\n",
    "    2. 一般把`文件大小 os.path.getsize(path)`传进去就可以了\n",
    "3. flags：映射区性质，默认是用共享\n",
    "    1. MAP_SHARED  共享（数据会自动同步磁盘）\n",
    "    2. MAP_PRIVATE 私有（不同步磁盘）\n",
    "4. prot：映射区权限，如果指定，就会提供内存保护（默认即可）\n",
    "    1. PROT_READ 读\n",
    "    2. PROT_READ | PROT_WRITE 写（必须有读的权限）\n",
    "5. *access：可以指定访问来代替flags和prot作为可选的关键字参数【这个是Python为了简化而添加的】*\n",
    "    1. ACCESS_READ：只读\n",
    "    2. ACCESS_WRITE：读和写（会影响内存和文件）\n",
    "    3. ACCESS_COPY：写时复制内存（影响内存，但不会更新基础文件）\n",
    "    4. *ACCESS_DEFAULT：延迟到prot（3.7才添加）*\n",
    "6. offset，偏移量，默认是0（和文件一致）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "b'\\x00'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 这个够明了了，\\0转换成二进制就是\\x00\n",
    "\"\\0\".encode()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u0000\n",
      "\u0000\n",
      "0\n",
      "1\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "# 老规矩，开始之前，扩充一个小知识点：(空字符串和'\\0'区别)\n",
    "a = \"\" # 空字符串 （Python里面没有char类型）\n",
    "b = \"\\x00\" # `\\0` 的二进制写法\n",
    "c = \"\\0\"\n",
    "\n",
    "print(a)\n",
    "print(b)\n",
    "print(c)\n",
    "\n",
    "print(len(a))\n",
    "print(len(b))\n",
    "print(len(c))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "看个简单的案例快速熟悉mmap模块：(大文件处理这块先不说，以后要是有机会讲数据分析的时候会再提)\n",
    "```py\n",
    "m.size()  # 查看文件大小\n",
    "m.seek(0)  # 修改Postion位置\n",
    "m.tell()  # 返回 m 对应文件的Postion位置\n",
    "m.read().translate(None, b\"\\x00\")  # 读取所有内容并把\\0删除\n",
    "m.closed  # 查看mmap是否关闭\n",
    "\n",
    "# 支持切片操作\n",
    "m[0:10] # 取值\n",
    "m[0:10] = b\"1234567890\"  # 赋值\n",
    "\n",
    "# 对自行模式大文件处理的同志，给个提示\n",
    "m.readline().decode() # 读一行，并转换成str\n",
    "m.size()==m.tell() # while循环退出条件\n",
    "```\n",
    "熟悉一下上面几个方法：\n",
    "```py\n",
    "import os\n",
    "import mmap\n",
    "\n",
    "def create_file(filename, size):\n",
    "    \"\"\"初始化一个文件，并把文件扩充到指定大小\"\"\"\n",
    "    with open(filename, \"wb\") as f:\n",
    "        f.seek(size - 1)  # 改变流的位置\n",
    "        f.write(b\"\\x00\")  # 在末尾写个`\\0`\n",
    "\n",
    "def main():\n",
    "    create_file(\"mmap_file\", 4096)  # 创建一个4k的文件\n",
    "    with mmap.mmap(os.open(\"mmap_file\", os.O_RDWR), 0) as m:  # 创建映射\n",
    "        print(m.size())  # 查看文件大小\n",
    "        m.resize(1024)  # 重新设置文件大小\n",
    "        print(len(m))  # len也一样查看文件大小\n",
    "        print(m.read().translate(None, b\"\\x00\"))  # 读取所有内容并把\\0删除\n",
    "        print(m.readline().decode())  # 读取一行，bytes转成str\n",
    "        print(m.tell())  # 返回 m 对应文件的当前位置\n",
    "        m.seek(0)  # 修改Postion位置\n",
    "        print(m.tell())  # 返回 m 对应文件的当前位置\n",
    "        print(m[0:10])  # 支持切片操作\n",
    "        print(\"postion_index:%d\" % m.tell())\n",
    "        m[0:10] = b\"1234567890\"  # 赋值\n",
    "        print(\"postion_index:%d\" % m.tell())\n",
    "        print(m[0:10])  # 取值\n",
    "        print(\"postion_index:%d\" % m.tell())\n",
    "        print(m[:].decode())  # 全部读出来\n",
    "    print(m.closed)  # 查看mmap是否关闭\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：(测试了一下，切片操作【读、写】不会影响postion)\n",
    "```\n",
    "4096\n",
    "1024\n",
    "b''\n",
    "\n",
    "1024\n",
    "0\n",
    "b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n",
    "postion_index:0\n",
    "postion_index:0\n",
    "b'1234567890'\n",
    "postion_index:0\n",
    "1234567890\n",
    "True\n",
    "```\n",
    "看下open打开的案例：\n",
    "```py\n",
    "import os\n",
    "import mmap\n",
    "\n",
    "def main():\n",
    "    with open(\"temp\", \"wb\") as f:\n",
    "        f.write(\"小明同学最爱刷碗\\n小潘同学最爱打扫\".encode())\n",
    "\n",
    "    # 打开磁盘二进制文件进行更新（读写）\n",
    "    with open(\"temp\", \"r+b\") as f:\n",
    "        with mmap.mmap(f.fileno(), 0) as m:\n",
    "            print(\"postion_index:%d\" % m.tell())\n",
    "            print(m.readline().decode().strip())  # 转成str并去除两端空格\n",
    "            print(\"postion_index:%d\" % m.tell())\n",
    "            print(m[:].decode())  # 全部读出来\n",
    "            print(\"postion_index:%d\" % m.tell())\n",
    "            m.seek(0)\n",
    "            print(\"postion_index:%d\" % m.tell())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "postion_index:0\n",
    "小明同学最爱刷碗\n",
    "postion_index:25\n",
    "小明同学最爱刷碗\n",
    "小潘同学最爱打扫\n",
    "postion_index:25\n",
    "postion_index:0\n",
    "```\n",
    "\n",
    "其他方法可以参考：<a href=\"https://www.cnblogs.com/zhoujinyi/p/6062907.html\" target=\"_blank\">这篇文章</a>（Python3很多都和Python2不太相同，辩证去看吧）\n",
    "\n",
    "注意一点：\n",
    "\n",
    "通过MMap内存映射之后，**进程间通信并不是对文件操作，而是在内存中**。文件保持同步只是因为mmap的flags默认设置的是共享模式（MAP_SHARED）\n",
    "\n",
    "PS：还记得之前讲<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9202988.html#1.8-实例方法、类方法、静态方法\" target=\"_blank\">类方法和实例方法</a>的时候吗？Python中类方法可以直接被对象便捷调用，这边**mmap实例对象中的方法，其实很多都是类方法**\n",
    "**步入正轨**：\n",
    "\n",
    "来看一个有血缘关系的通信案例：（一般用匿名）\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import mmap\n",
    "\n",
    "def create_file(file_name, size):\n",
    "    with open(file_name, \"wb\") as f:\n",
    "        f.seek(size - 1)\n",
    "        f.write(b\"\\0x00\")\n",
    "\n",
    "def main():\n",
    "    file_name = \"temp.bin\"\n",
    "    # mmap映射的时候不能映射空文件，所以我们自己创建一个\n",
    "    create_file(file_name, 1024)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDWR)\n",
    "    with mmap.mmap(fd, 0) as m:  # m.resize(1024) # 大小可以自己调整的\n",
    "        pid = os.fork()\n",
    "        if pid == 0:\n",
    "            print(\"[子进程]PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "            m.write(\"子进程说：老爸，我想出去玩了～\\n\".encode())\n",
    "            time.sleep(3)\n",
    "            print(m.readline().decode().strip())\n",
    "            exit(0)\n",
    "        elif pid > 0:\n",
    "            print(\"[父进程]PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "            time.sleep(1)  # 和文件一样，非堵塞\n",
    "            print(m.readline().decode().strip())\n",
    "            m.write(\"父进程说：去吧去吧\\n\".encode())\n",
    "            wpid, status = os.wait()\n",
    "            print(\"[父进程]收尸：PID:%d，Status:%d\" % (wpid, status))\n",
    "            exit(0)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[父进程]PID:6843，PPID:3274\n",
    "[子进程]PID:6844，PPID:6843\n",
    "子进程说：老爸，我想出去玩了～\n",
    "父进程说：去吧去吧\n",
    "[父进程]收尸：PID:6844，Status:0\n",
    "```\n",
    "\n",
    "#### 有血缘关系使用MMAP通信\n",
    "\n",
    "父进程创建了一份mmap对象，fork产生子进程的时候相当于copy了一份指向，所以可以进行直接通信（联想fd的copy）\n",
    "\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import mmap\n",
    "\n",
    "def main():\n",
    "    # 不记录文件中，直接内存中读写（这个地方len就不能为0了，自己指定一个大小eg：4k）\n",
    "    with mmap.mmap(-1, 4096) as m:\n",
    "        pid = os.fork()\n",
    "        if pid == 0:\n",
    "            print(\"[子进程]PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "            m.write(\"[子进程]老爸我出去嗨了～\\n\".encode())\n",
    "            time.sleep(2)\n",
    "            msg = m.readline().decode().strip()\n",
    "            print(msg)\n",
    "            exit(0)\n",
    "        elif pid > 0:\n",
    "            print(\"[父进程]PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "            time.sleep(1)\n",
    "            msg = m.readline().decode().strip()\n",
    "            print(msg)\n",
    "            m.write(\"[父进程]去吧，皮卡丘～\".encode())\n",
    "\n",
    "            wpid, status = os.wait()\n",
    "            print(\"[父进程]收尸：PID:%d，Status:%d\" % (wpid, status))\n",
    "            exit(0)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[父进程]PID:8115，PPID:3274\n",
    "[子进程]PID:8116，PPID:8115\n",
    "[子进程]老爸我出去嗨了～\n",
    "[父进程]去吧，皮卡丘～\n",
    "[父进程]收尸：PID:8116，Status:0\n",
    "```\n",
    "\n",
    "#### 无血缘关系使用MMAP通信\n",
    "\n",
    "因为不同进程之前没有关联，必须以文件为媒介（文件描述符fd）\n",
    "\n",
    "进程1：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import mmap\n",
    "\n",
    "def create_file(file_name, size):\n",
    "    with open(file_name, \"wb\") as f:\n",
    "        f.seek(size - 1)\n",
    "        f.write(b\"\\0x00\")\n",
    "\n",
    "def main():\n",
    "    file_name = \"temp.bin\"\n",
    "\n",
    "    if not os.path.exists(file_name):\n",
    "        # mmap映射的时候不能映射空文件，所以我们自己创建一个\n",
    "        create_file(file_name, 1024)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDWR)\n",
    "    with mmap.mmap(fd, 0) as m:  # m.resize(1024) # 大小可以自己调整的\n",
    "        print(\"[进程1]PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "        m.write(\"进程1说：小明放学去撸串吗？\\n\".encode())\n",
    "        time.sleep(3)\n",
    "        print(m.readline().decode().strip())\n",
    "        exit(0)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "进程2：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import mmap\n",
    "\n",
    "def create_file(file_name, size):\n",
    "    with open(file_name, \"wb\") as f:\n",
    "        f.seek(size - 1)\n",
    "        f.write(b\"\\0x00\")\n",
    "\n",
    "def main():\n",
    "    file_name = \"temp.bin\"\n",
    "\n",
    "    if not os.path.exists(file_name):\n",
    "        # mmap映射的时候不能映射空文件，所以我们自己创建一个\n",
    "        create_file(file_name, 1024)\n",
    "\n",
    "    fd = os.open(file_name, os.O_RDWR)\n",
    "    with mmap.mmap(fd, 0) as m:  # m.resize(1024) # 大小可以自己调整的\n",
    "        print(\"[进程2]PID:%d，PPID:%d\" % (os.getpid(), os.getppid()))\n",
    "        time.sleep(1)\n",
    "        print(m.readline().decode().strip())\n",
    "        m.write(\"进程2说：为毛不去？\\n\".encode())\n",
    "        exit(0)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出图示：\n",
    "![2.mmap无血缘关系进程通信](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180729054655551-1740522040.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4.6.进程间通信～Signal信号\n",
    "\n",
    "代码实例：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/6.signal\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程通信/6.signal</a>\n",
    "\n",
    "<a href=\"https://baike.baidu.com/item/信号/7927794\" target=\"_blank\">信号</a>：它是一种异步的通知机制，用来提醒进程一个事件已经发生。当一个信号发送给一个进程，操作系统中断了进程正常的控制流程，此时，任何非原子操作都将被中断。如果进程定义了信号的处理函数，那么它将被执行，否则就执行默认的处理函数。\n",
    "\n",
    "一般信号不太用于进程间通信，常用就是发个信号把xxx进程干死。\n",
    "\n",
    "先来个例子，等会讲理论：\n",
    "\n",
    "Python里面一般用`os.kill(pid,signalnum)`来发信号：eg：`kill 9 pid`\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import signal\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"[子进程]PID=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        while True:\n",
    "            print(\"[子进程]孩子老卵，怎么滴吧～\")\n",
    "            time.sleep(1)\n",
    "    elif pid > 0:\n",
    "        print(\"[父进程]PID=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        time.sleep(3)\n",
    "        print(\"父进程耐心有限，准备杀了儿子\")\n",
    "\n",
    "        # sigkill 相当于kill 9 pid\n",
    "        os.kill(pid, signal.SIGKILL)  # 发信号\n",
    "\n",
    "        # 收尸\n",
    "        wpid, status = os.wait()\n",
    "        print(\"父进程收尸：子进程PID=%d,Status=%d\" % (wpid, status))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[父进程]PID=21841,PPID=5559\n",
    "[子进程]PID=21842,PPID=21841\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "父进程耐心有限，准备杀了儿子\n",
    "父进程收尸：子进程PID=21842,Status=9\n",
    "```\n",
    "扩展一下：\n",
    "1. `signal.pthread_kill(thread_id,signal.SIGKILL))  # 杀死线程`\n",
    "2. `os.abort()  # 给自己发异常终止信号`\n",
    "\n",
    "#### 理论开始\n",
    "\n",
    "这边开始说说理论：\n",
    "\n",
    "**信号状态**：\n",
    "1. 产生状态\n",
    "2. 未决状态（信号产生后没有被处理）\n",
    "3. 递达状态（信号已经传达到进程中）\n",
    "\n",
    "**产生、传递**等都是通过内核进行的，结合上面的例子画个图理解下：\n",
    "![3.signal图示](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180729162253198-1772478445.png)\n",
    "\n",
    "未决信号集：没有被当前进程处理的信号集合（可以通过`signal.sigpending()`获取`set`集合）\n",
    "\n",
    "阻塞信号集：要屏蔽的信号（不能被用户操作）\n",
    "\n",
    "回顾一下上面说`kill 9 pid`原理的知识：`kill -l`\n",
    "```\n",
    " 1) SIGHUP\t 2) SIGINT\t 3) SIGQUIT\t 4) SIGILL\t 5) SIGTRAP\n",
    " 6) SIGABRT\t 7) SIGBUS\t 8) SIGFPE\t 9) SIGKILL\t10) SIGUSR1\n",
    "11) SIGSEGV\t12) SIGUSR2\t13) SIGPIPE\t14) SIGALRM\t15) SIGTERM\n",
    "16) SIGSTKFLT\t17) SIGCHLD\t18) SIGCONT\t19) SIGSTOP\t20) SIGTSTP\n",
    "21) SIGTTIN\t22) SIGTTOU\t23) SIGURG\t24) SIGXCPU\t25) SIGXFSZ\n",
    "26) SIGVTALRM\t27) SIGPROF\t28) SIGWINCH\t29) SIGIO\t30) SIGPWR\n",
    "31) SIGSYS\t34) SIGRTMIN\t35) SIGRTMIN+1\t36) SIGRTMIN+2\t37) SIGRTMIN+3\n",
    "38) SIGRTMIN+4\t39) SIGRTMIN+5\t40) SIGRTMIN+6\t41) SIGRTMIN+7\t42) SIGRTMIN+8\n",
    "43) SIGRTMIN+9\t44) SIGRTMIN+10\t45) SIGRTMIN+11\t46) SIGRTMIN+12\t47) SIGRTMIN+13\n",
    "48) SIGRTMIN+14\t49) SIGRTMIN+15\t50) SIGRTMAX-14\t51) SIGRTMAX-13\t52) SIGRTMAX-12\n",
    "53) SIGRTMAX-11\t54) SIGRTMAX-10\t55) SIGRTMAX-9\t56) SIGRTMAX-8\t57) SIGRTMAX-7\n",
    "58) SIGRTMAX-6\t59) SIGRTMAX-5\t60) SIGRTMAX-4\t61) SIGRTMAX-3\t62) SIGRTMAX-2\n",
    "63) SIGRTMAX-1\t64) SIGRTMAX\n",
    "```\n",
    "说下常用的几个信号：\n",
    "1. 9号信号（`sigkill`）是`kill 9`\n",
    "2. 2号信号（`sigint`）是`Ctrl+C`终止进程\n",
    "3. 3号信号（`sigquit`）是`Ctrl+\\`终止进程\n",
    "\n",
    "#### 信号捕捉\n",
    "\n",
    "现在说说信号捕捉`signal.signal(signalnum, handler)`\n",
    "\n",
    "`handler处理函数`，除了自定义信号处理函数外也可以使用系统提供的两种方式：\n",
    "1. `SIG_IGN`（忽略该信号）\n",
    "2. `SIG_DFL`（系统默认操作）\n",
    "\n",
    "注意一点：`SIGSTOP` 和 `SIGKILL` 信号是不能被捕获、忽略和阻塞的（这个是系统预留的，如果连预留都没有可以想象肯定木马横向）\n",
    "\n",
    "PS:**信号的优先级**一般都是**比较高**的,往往**进程收到信号后都会停下手上的事情先处理信号**（死循环也一样歇菜）\n",
    "\n",
    "来看一个例子:(处理singint，忽略sigquit)\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import signal\n",
    "\n",
    "def print_info(signalnum, frame):\n",
    "    print(\"信号:%d准备弄我,我是小强我怕谁?(%s)\" % (signalnum, frame))\n",
    "\n",
    "def main():\n",
    "    signal.signal(signal.SIGINT, print_info)  # 处理Ctrl+C的终止命令(singint)\n",
    "    signal.signal(signal.SIGQUIT, signal.SIG_IGN)  # 忽略Ctrl+\\的终止命令(sigquit)\n",
    "\n",
    "    while True:\n",
    "        print(\"[PID:%d]我很坚强,不退出,等着信号来递达~\" % os.getpid())\n",
    "        time.sleep(3)  # 你要保证进程不会退出才能处理信号,不用担心影响信号（优先级高）\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出图示:（我休息3s，在3s内给程序发送了`sigint`信号（Ctrl+C）就立马处理了）\n",
    "![signal信号捕捉](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180729164618029-1946929329.gif)\n",
    "\n",
    "扩展：\n",
    "1. 如果你只是等一个信号就退出，可以使用：`signal.pause()`，不必使用死循环来轮询了\n",
    "2. `os.killpg(pgid, sid)`进程组结束\n",
    "3. `signal.siginterrupt(signal.SIGALRM, False)` 防止系统调用被信号打断所设立（其实一般也不太用，出问题才用）\n",
    "\n",
    "通俗的讲就是，要是系统和你发一样的信号可能也就被处理了，加上这句就ok了，eg：\n",
    "\n",
    "举个例子，有时候有些恶意程序蓄意破坏或者被所谓的安全软件误杀比如系统函数`kill(-1)`【有权限的都杀了】\n",
    "```py\n",
    "import signal\n",
    "\n",
    "def print_info(signalnum, frame):\n",
    "    print(\"死前留言：我被信号%d弄死了，记得替我报仇啊！\" % signalnum)\n",
    "\n",
    "def main():\n",
    "    signal.signal(signal.SIGINT, print_info)  # 处理Ctrl+C的终止命令(singint)\n",
    "    signal.signal(signal.SIGQUIT, print_info)  # 处理Ctrl+\\的终止命令(singquit)\n",
    "    signal.siginterrupt(signal.SIGINT, False)\n",
    "    signal.siginterrupt(signal.SIGQUIT, False)\n",
    "    signal.pause()  # 设置一个进程到休眠状态直到接收一个信号\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "dnt@MZY-PC:~/桌面/work/BaseCode/python/5.concurrent/Linux/进程通信/6.signal python3 1.os_kill2.py \n",
    "^C死前留言：我被信号2弄死了，记得替我报仇啊！\n",
    "dnt@MZY-PC:~/桌面/work/BaseCode/python/5.concurrent/Linux/进程通信/6.signal python3 1.os_kill2.py \n",
    "^\\死前留言：我被信号3弄死了，记得替我报仇啊！\n",
    "dnt@MZY-PC:~/桌面/work/BaseCode/python/5.concurrent/Linux/进程通信/6.signal \n",
    "```\n",
    "\n",
    "#### 定时器alarm（执行一次）\n",
    "\n",
    "再说两个定时器就进下一个话题把，这个主要就是**信号捕捉用得比较多**，然后就是**一般都是守护进程发信号**\n",
    "\n",
    "先验证一个概念：**alarm闹钟不能被fork后的子进程继承**\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import signal\n",
    "\n",
    "def main():\n",
    "    # 不受进程影响，每个进程只能有一个定时器，再设置只是重置\n",
    "    signal.alarm(3)  # 设置终止时间（3s），然后终止进程（sigaltirm）\n",
    "\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        print(\"[子进程]PID=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "        for i in range(5):\n",
    "            print(\"[子进程]孩子老卵，怎么滴吧～\")\n",
    "            time.sleep(1)\n",
    "    elif pid > 0:\n",
    "        print(\"[父进程]PID=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "    print(\"[遗言]PID=%d,PPID=%d\" % (os.getpid(), os.getppid()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出\n",
    "```\n",
    "[父进程]PID=9687,PPID=9063\n",
    "[遗言]PID=9687,PPID=9063\n",
    "[子进程]PID=9688,PPID=9687\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[子进程]孩子老卵，怎么滴吧～\n",
    "[遗言]PID=9688,PPID=1060\n",
    "```\n",
    "这个你可以自己验证：**不受进程影响，每个进程只能有一个定时器，再设置只是重置**\n",
    "\n",
    "#### 普及一个小技巧\n",
    "\n",
    "其实好好看逆天的问题都会发现各种小技巧的，所有小技巧自我总结一下就会产生质变了\n",
    "\n",
    "```py\n",
    "import signal\n",
    "\n",
    "def main():\n",
    "    signal.alarm(1)  # 设置终止时间（3s），然后终止进程（sigaltirm）\n",
    "    i = 0\n",
    "    while True:\n",
    "        print(i)\n",
    "        i += 1  # 别忘记，Python里面没有++哦～\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行一下：**`time python3 xxx.py`**\n",
    "![time1](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180729104653284-401486532.png)\n",
    "运行一下：**`time python3 xxx.py > temp`**\n",
    "![time2](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180729104514041-1693000606.png)\n",
    "\n",
    "简单说下三个参数：\n",
    "1. `real`总共运行时间（real=user+sys+损耗时间）\n",
    "2. `user`（用户代码真正运行时间）\n",
    "3. `sys`（内核运行时间）【内核不运行，你系统也不正常了】\n",
    "\n",
    "其实就是减少了IO操作，性能方面就相差几倍！我这边只是一台老电脑，要是真在服务器下性能相差可能让你吓一跳\n",
    "\n",
    "现在知道为什么要realase发布而不用debug直接部署了吧（**线上项目非必要情况，一般都会删除所有日记输出的**）\n",
    "\n",
    "#### 定时器setitimer（周期执行）\n",
    "\n",
    "`signal.setitimer(which, seconds, interval=0.0)` which参数说明：\n",
    "1. **signal.TIMER_REAL：按实际时间计时，计时到达将给进程发送SIGALRM信号**\n",
    "2. signal.ITIMER_VIRTUAL：仅当进程执行时才进行计时。计时到达将发送SIGVTALRM信号给进程。\n",
    "3. signal.ITIMER_PROF：当进程执行时和系统为该进程执行动作时都计时。与ITIMER_VIRTUAL是一对，该定时器经常用来统计进程在用户态和内核态花费的时间。计时到达将发送SIGPROF信号给进程。\n",
    "\n",
    "这个一般在守护进程中经常用，看个简单案例：\n",
    "\n",
    "```py\n",
    "import time\n",
    "import signal\n",
    "\n",
    "def say_hai(signalnum, frame):\n",
    "    print(\"我会周期性执行哦～\")\n",
    "\n",
    "def main():\n",
    "    # 捕捉信号（在前面最好，不然容易漏捕获）\n",
    "    signal.signal(signal.SIGALRM, say_hai)\n",
    "    # 设置定时器，第一次1s后执行，以后都3s执行一次\n",
    "    signal.setitimer(signal.ITIMER_REAL, 1, 3)\n",
    "    # print(signal.getitimer(signal.ITIMER_REAL))\n",
    "\n",
    "    while True:\n",
    "        print(\"我在做其他事情\")\n",
    "        time.sleep(1)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "我在做其他事情\n",
    "我会周期性执行哦～\n",
    "我在做其他事情\n",
    "我在做其他事情\n",
    "我在做其他事情\n",
    "我会周期性执行哦～\n",
    "我在做其他事情\n",
    "我在做其他事情\n",
    "我在做其他事情\n",
    "我会周期性执行哦～\n",
    "我在做其他事情\n",
    "我在做其他事情\n",
    "我在做其他事情\n",
    "...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4.7.进程守护\n",
    "\n",
    "实例代码：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程守护\" target=\"_blank\">\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Linux/进程守护</a>\n",
    "\n",
    "守护进程应用场景很多，比如程序上线后有个bug被不定时的触发，每次都导致系统爆卡或者退出，而程序员修复bug需要时间，但是线上项目又不能挂，这时候就可以使用一个心跳检测的守护进程（查错也可以使用守护进程）【为恶就不说了】\n",
    "\n",
    "正式开始前，先来个伪案例：\n",
    "\n",
    "模拟一个漏洞百出的程序\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    print(\"[PID:%d]进程运行中...\" % os.getpid())\n",
    "    time.sleep(5)\n",
    "    os.abort()  # 给自己发异常终止信号\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "写个简单版本的守护进程：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import signal\n",
    "\n",
    "def write_log(msg):\n",
    "    pass\n",
    "\n",
    "def is_running(p_name):\n",
    "    \"\"\"是否在运行\"\"\"\n",
    "    try:\n",
    "        # grep -v grep 不显示grep本身，wc -l是计数用的\n",
    "        result = os.popen(\"ps ax | grep %s | grep -v grep\" % p_name).readlines()\n",
    "        if len(result) > 0:\n",
    "            return True\n",
    "        else:\n",
    "            return False\n",
    "    except Exception as ex:\n",
    "        write_log(ex)\n",
    "        return False\n",
    "\n",
    "def is_restart(p_script):\n",
    "    \"\"\"重启程序\"\"\"\n",
    "    try:\n",
    "        if os.system(p_script) == 0:\n",
    "            return True\n",
    "        else:\n",
    "            return False\n",
    "    except Exception as ex:\n",
    "        write_log(ex)\n",
    "        return False\n",
    "\n",
    "def heartbeat(signalnum, frame):\n",
    "    \"\"\"心跳检查\"\"\"\n",
    "    p_name = \"test.py\"\n",
    "    p_script = \"python3 ./test.py\"\n",
    "\n",
    "    if not is_running(p_name):\n",
    "        print(\"程序(%s)已挂，准备重启\" % p_name)\n",
    "        if not is_restart(p_script):\n",
    "            is_restart(p_script)  # 再给一次机会\n",
    "\n",
    "def main():\n",
    "    # 信号处理\n",
    "    signal.signal(signal.SIGALRM, heartbeat)\n",
    "    # 第一次1s后检查，以后每5s检查一次\n",
    "    signal.setitimer(signal.ITIMER_REAL, 1, 5)\n",
    "    while True:\n",
    "        time.sleep(5)  # 不用担心影响signal（优先级别高）\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "程序(test.py)已挂，准备重启\n",
    "[PID:7270]进程运行中...\n",
    "Aborted (core dumped)\n",
    "程序(test.py)已挂，准备重启\n",
    "[PID:7278]进程运行中...\n",
    "Aborted (core dumped)\n",
    "[PID:7284]进程运行中...\n",
    ".....\n",
    "```\n",
    "\n",
    "#### 正规流程的守护进程\n",
    "\n",
    "写了个伪牌子的，现在说说正规的，看看概念的东西：\n",
    "\n",
    "**特点**：\n",
    "1. 后台服务进程\n",
    "2. 脱离于控制终端（setpid）\n",
    "3. 周期性的执行某个任务|等待某个事件发生（setitimer）\n",
    "4. 不受用户登录注销影响（关机影响，不过你可以添加启动项）\n",
    "5. 一般使用以d结尾的服务名称（约定俗成）\n",
    "\n",
    "讲正式流程前先复习一下上面说的`进程组`和`会话`\n",
    "1. 进程组：每一个进程都属于一个“进程组”，当一个进程被创建的时候，它默认是其父进程所在组的成员（**你们一家**）\n",
    "2. 会  话：几个进程组又构成一个会话（**你们小区**）\n",
    "\n",
    "需要扩充几点：\n",
    "1. **进程组**：\n",
    "    1. 组长：第一个进程\n",
    "    2. 组长ID==进程组ID\n",
    "    3. 组长挂了不影响进程组\n",
    "\n",
    "2. **会话**：\n",
    "    1. 组长不能创建会话（你都有官了，不留点门路给后人？）\n",
    "    2. 创建会话的进程成为新进程组的组长（新进程组里面就它一个嘛）\n",
    "    3. 创建出新会话会丢弃原有的控制终端（到了新环境里面，人脉得重新建立）\n",
    "\n",
    "稍微验证一下，然后步入正题：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    pid = os.fork()\n",
    "    if pid == 0:\n",
    "        for i in range(7):\n",
    "            print(\"子进程：PID=%d,PPID=%d,PGrpID=%d\" % (os.getpid(), os.getppid(), os.getpgrp()))\n",
    "            time.sleep(i)\n",
    "    elif pid > 0:\n",
    "        print(\"父进程：PID=%d,PPID=%d,PGrpID=%d\" % (os.getpid(), os.getppid(), os.getpgrp()))\n",
    "        time.sleep(4)\n",
    "\n",
    "    print(\"遗言：PID=%d,PPID=%d,PGrpID=%d\" % (os.getpid(), os.getppid(), os.getpgrp()))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "验证结果：`父进程ID==进程组ID`，`父进程挂了进程组依旧在`，顺便验证了下`ps -ajx`的参数\n",
    "![7.psjax](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180730052716451-1335691435.png)\n",
    "\n",
    "先看看这个SessionID是啥：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "\n",
    "def main():\n",
    "    print(\"进程：PID=%d,PPID=%d,PGrpID=%d\" % (os.getpid(), os.getppid(), os.getpgrp()))\n",
    "    print(os.getsid(os.getpid()))\n",
    "    for i in range(1, 5):\n",
    "        time.sleep(i)\n",
    "    print(\"over\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "**`ps ajx`**的参数现在全知道了：**PPID   PID  PGID   SID** (你不加grep就能看到的)\n",
    "![session_test]](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180730053900042-1627085753.png)\n",
    "\n",
    "验证一下SessionID的事情："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进程：PPID=3301,PID=2588,GID=3301,SID=3301\n"
     ]
    },
    {
     "ename": "PermissionError",
     "evalue": "[Errno 1] Operation not permitted",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mPermissionError\u001b[0m                           Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-1-375f70009fcf>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      9\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m'__main__'\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m     \u001b[0mmain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m<ipython-input-1-375f70009fcf>\u001b[0m in \u001b[0;36mmain\u001b[0;34m()\u001b[0m\n\u001b[1;32m      4\u001b[0m     \u001b[0mpid\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgetpid\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"进程：PPID=%d,PID=%d,GID=%d,SID=%d\"\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mpid\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgetppid\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgetpgrp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgetsid\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpid\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m     \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msetsid\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# 父进程没法设置为会话ID的验证\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mPermissionError\u001b[0m: [Errno 1] Operation not permitted"
     ]
    }
   ],
   "source": [
    "# 验证一下父进程不能创建会话ID\n",
    "import os\n",
    "\n",
    "def main():\n",
    "    pid = os.getpid()\n",
    "    print(\"进程：PPID=%d,PID=%d,GID=%d,SID=%d\" % (pid, os.getppid(), os.getpgrp(),os.getsid(pid)))\n",
    "    os.setsid() # 父进程没法设置为会话ID的验证\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "步入正轨：\n",
    "\n",
    "**创建守护进程的步骤**：\n",
    "1. fork子进程，父进程退出（子进程变成了孤儿）\n",
    "2. 子进程创建新会话（创建出新会话会丢弃原有的控制终端）\n",
    "3. 改变当前工作目录【为了减少bug】（eg：你在某个文件夹下运行，这个文件夹被删了，多少会点受影响）\n",
    "4. 重置文件掩码（继承了父进程的文件掩码，通过`umask(0)`重置一下，这样可以获取777权限）\n",
    "5. 关闭文件描述符（既然用不到了，就关了）\n",
    "6. 自己的逻辑代码\n",
    "\n",
    "先简单弄个例子实现上面步骤：\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "from sys import stdin, stdout, stderr\n",
    "\n",
    "def main():\n",
    "\n",
    "    # 【必须】1. fork子进程，父进程退出（子进程变成了孤儿）\n",
    "    pid = os.fork()\n",
    "    if pid > 0:\n",
    "        exit(0)\n",
    "\n",
    "    # 【必须】2. 子进程创建新会话（创建出新会话会丢弃原有的控制终端）\n",
    "    os.setsid()\n",
    "\n",
    "    # 3. 改变当前工作目录【为了减少bug】# 改成不会被删掉的目录，比如/\n",
    "    os.chdir(\"/home/dnt\")  # 我这边因为是用户创建的守护进程，就放它下面，用户删了，它也没必要存在了\n",
    "\n",
    "    # 4. 重置文件掩码（获取777权限）\n",
    "    os.umask(0)\n",
    "\n",
    "    # 5. 关闭文件描述符（如果写日志也可以重定向一下）\n",
    "    os.close(stdin.fileno())\n",
    "    os.close(stdout.fileno())\n",
    "    os.close(stderr.fileno())\n",
    "\n",
    "    # 【必须】6. 自己的逻辑代码\n",
    "    while True:\n",
    "        time.sleep(1)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行效果：（直接后台走起了）\n",
    "![create_pro](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180730061004184-1729802785.png)\n",
    "\n",
    "---\n",
    "#### 基础回顾\n",
    "\n",
    "**如果对Linux基础不熟，可以看看几年前说的LinuxBase：**\n",
    "\n",
    "Linux基础命令：<a href=\"http://www.cnblogs.com/dunitian/p/4822807.html\" target=\"_blank\">http://www.cnblogs.com/dunitian/p/4822807.html</a>\n",
    "\n",
    "Linux系列其他文章：<a href=\"https://www.cnblogs.com/dunitian/p/4822808.html#linux\" target=\"_blank\">https://www.cnblogs.com/dunitian/p/4822808.html#linux</a>\n",
    "\n",
    "---\n",
    "\n",
    "**如果对部署运行系列不是很熟，可以看之前写的小demo：**\n",
    "\n",
    "用Python3、NetCore、Shell分别开发一个Ubuntu版的定时提醒（附NetCore跨平台两种发布方式）：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9111200.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9111200.html</a>\n",
    "\n",
    "---\n",
    "\n",
    "**如果对OOP不是很熟悉可以查看之前写的OOP文章：**\n",
    "\n",
    "Python3 与 C# 面向对象之～封装<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9202988.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9202988.html</a>\n",
    "\n",
    "Python3 与 C# 面向对象之～继承与多态<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9219226.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9219226.html</a>\n",
    "\n",
    "Python3 与 C# 面向对象之～异常相关<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9219751.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9219751.html</a>\n",
    "\n",
    "---\n",
    "\n",
    "**如果基础不牢固，可以看之前写的PythonBase：**\n",
    "\n",
    "Python3 与 C# 基础语法对比（Function专栏）<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9175950.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9175950.html</a>\n",
    "\n",
    "Python3 与 C# 扩展之～模块专栏<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9253087.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9253087.html</a>\n",
    "\n",
    "Python3 与 C# 扩展之～基础衍生<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9278573.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9278573.html</a>\n",
    "\n",
    "Python3 与 C# 扩展之～基础拓展<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9333792.html\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9333792.html</a>\n",
    "\n",
    "---\n",
    "\n",
    "现在正儿八经的来个**简化版的守护进程**：（你可以根据需求多加点信号处理）\n",
    "```py\n",
    "import os\n",
    "import time\n",
    "import signal\n",
    "from sys import stdin, stdout, stderr\n",
    "\n",
    "class Daemon(object):\n",
    "    def __init__(self, p_name, p_script):\n",
    "        self.p_name = p_name\n",
    "        self.p_script = p_script\n",
    "\n",
    "    @staticmethod\n",
    "    def write_log(msg):\n",
    "        # 追加方式写\n",
    "        with open(\"info.log\", \"a+\") as f:\n",
    "            f.write(msg)\n",
    "            f.write(\"\\n\")\n",
    "\n",
    "    def is_running(self, p_name):\n",
    "        \"\"\"是否在运行\"\"\"\n",
    "        try:\n",
    "            # grep -v grep 不显示grep本身，wc -l是计数用的\n",
    "            result = os.popen(\n",
    "                \"ps ax | grep %s | grep -v grep\" % p_name).readlines()\n",
    "            if len(result) > 0:\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        except Exception as ex:\n",
    "            self.write_log(ex)\n",
    "            return False\n",
    "\n",
    "    def is_restart(self, p_script):\n",
    "        \"\"\"重启程序\"\"\"\n",
    "        try:\n",
    "            if os.system(p_script) == 0:\n",
    "                return True\n",
    "            else:\n",
    "                return False\n",
    "        except Exception as ex:\n",
    "            self.write_log(ex)\n",
    "            return False\n",
    "\n",
    "    def heartbeat(self, signalnum, frame):\n",
    "        \"\"\"心跳检查\"\"\"\n",
    "        if not self.is_running(self.p_name):\n",
    "            self.write_log(\"[%s]程序(%s)已挂，准备重启\" % (time.strftime(\"%Y-%m-%d %X\"),\n",
    "                                                  self.p_name))\n",
    "            if not self.is_restart(self.p_script):\n",
    "                self.is_restart(self.p_script)  # 再给一次机会\n",
    "\n",
    "    def run(self):\n",
    "        \"\"\"运行守护进程\"\"\"\n",
    "        pid = os.fork()\n",
    "        if pid > 0:\n",
    "            exit(0)\n",
    "\n",
    "        os.setsid()  # 子进程创建新会话\n",
    "        os.chdir(\"/home/dnt\")  # 改变当前工作目录\n",
    "        os.umask(0)  # 获取777权限\n",
    "\n",
    "        # 5. 关闭文件描述符\n",
    "        os.close(stdin.fileno())\n",
    "        os.close(stdout.fileno())\n",
    "        os.close(stderr.fileno())\n",
    "\n",
    "        # 【必须】6. 自己的逻辑代码\n",
    "        # 捕捉设置的定时器\n",
    "        signal.signal(signal.SIGALRM, self.heartbeat)\n",
    "        # 第一次2s后执行，以后5s执行一次\n",
    "        signal.setitimer(signal.ITIMER_REAL, 2, 5)\n",
    "\n",
    "        self.write_log(\"[%s]daeman running\" % time.strftime(\"%Y-%m-%d %X\"))\n",
    "        self.write_log(\"p_name:%s，p_script:%s\" % (self.p_name, self.p_script))\n",
    "\n",
    "        while True:\n",
    "            time.sleep(5)  # 不用担心影响signal（优先级别高）\n",
    "\n",
    "def main():\n",
    "    try:\n",
    "        pro = Daemon(\"test.py\", \"python3 ~/demo/test.py\")\n",
    "        pro.run()\n",
    "    except Exception as ex:\n",
    "        Daemon.write_log(ex)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行效果：(关闭文件描述符后就不要printf了)\n",
    "\n",
    "![10.mini](https://images2018.cnblogs.com/blog/1127869/201807/1127869-20180730090146834-1230082672.png)\n",
    "\n",
    "扩展说明，如果你要文件描述符重定向的话可以这么写：\n",
    "```py\n",
    "with open(\"in.log\", \"a+\") as f:\n",
    "    os.dup2(f.fileno(), sys.stdin.fileno())\n",
    "with open(\"out.log\", \"a+\") as f:\n",
    "    os.dup2(f.fileno(), sys.stdout.fileno())\n",
    "with open(\"err.log\", \"a+\") as f:\n",
    "    os.dup2(f.fileno(), sys.stderr.fileno())\n",
    "```\n",
    "之后你printf就自动到指定的文件了"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 扩展说明：\n",
    "\n",
    "Socket，在讲基础最后一个系列～**网络编程**的时候会讲，不急，而且进程间通信不需要这么`‘重量级’`的\n",
    "\n",
    "线程相关打算和代码一起讲，有机会也可以单独拉出来说一个结尾篇\n",
    "\n",
    "---\n",
    "\n",
    "业余拓展：\n",
    "\n",
    "<a href=\"https://docs.python.org/3/contents.html\" target=\"_blank\">官方文档大全</a>\n",
    "\n",
    "<a href=\"https://docs.python.org/3/library/ipc.html\" target=\"_blank\">进程间通信和网络</a>\n",
    "\n",
    "<a href=\"https://docs.python.org/3/library/os.html\" target=\"_blank\">os - 其他操作系统接口</a>\n",
    "\n",
    "<a href=\"https://docs.python.org/3/library/mmap.html\" target=\"_blank\">mmap - 内存映射文件支持</a>\n",
    "\n",
    "<a href=\"https://docs.python.org/3/library/signal.html\" target=\"_blank\">signal - 设置异步事件的处理程序</a>\n",
    "\n",
    "Other：\n",
    "```\n",
    "Linux下0、1、2号进程\n",
    "https://blog.csdn.net/gatieme/article/details/51484562\n",
    "https://blog.csdn.net/gatieme/article/details/51532804\n",
    "https://blog.csdn.net/gatieme/article/details/51566690\n",
    "\n",
    "Linux 的启动流程\n",
    "http://www.ruanyifeng.com/blog/2013/08/linux_boot_process.html\n",
    "http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html\n",
    "http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-part-two.html\n",
    "\n",
    "孤儿进程与僵尸进程\n",
    "https://www.cnblogs.com/Anker/p/3271773.html\n",
    "https://blog.csdn.net/believe_s/article/details/77040494\n",
    "\n",
    "Python2 OS模块之进程管理\n",
    "https://www.cnblogs.com/now-fighting/p/3534185.html\n",
    "\n",
    "缓冲区的个人理解\n",
    "https://blog.csdn.net/lina_acm/article/details/51865543\n",
    "\n",
    "深入Python多进程编程基础\n",
    "https://zhuanlan.zhihu.com/p/37370577\n",
    "https://zhuanlan.zhihu.com/p/37370601\n",
    "\n",
    "python多进程实现进程间通信实例\n",
    "https://www.jb51.net/article/129016.htm\n",
    "\n",
    "PIPE2参考：\n",
    "https://bugs.python.org/file22147/posix_pipe2.diff\n",
    "https://stackoverflow.com/questions/30087506/event-driven-system-call-in-python\n",
    "https://stackoverflow.com/questions/5308080/python-socket-accept-nonblocking/5308168\n",
    "\n",
    "FIFO参考：\n",
    "https://blog.csdn.net/an_tang/article/details/68951819\n",
    "https://blog.csdn.net/firefoxbug/article/details/8137762\n",
    "\n",
    "Python之mmap内存映射模块（大文本处理）说明\n",
    "https://www.cnblogs.com/zhoujinyi/p/6062907.html\n",
    "\n",
    "python 基于mmap模块的jsonmmap实现本地多进程内存共享\n",
    "https://www.cnblogs.com/dacainiao/p/5914114.html\n",
    "\n",
    "如果把一个事务可看作是一个程序,它要么完整的被执行,要么完全不执行。这种特性就叫原子性。\n",
    "https://blog.csdn.net/Android_Mrchen/article/details/77866490\n",
    "\n",
    "事务四大特征：原子性，一致性，隔离性和持久性\n",
    "https://blog.csdn.net/u014079773/article/details/52808193\n",
    "\n",
    "python 、mmap 实现内存数据共享\n",
    "https://www.jianshu.com/p/c3afc0f02560\n",
    "http://www.cnblogs.com/zhoujinyi/p/6062907.html\n",
    "https://blog.csdn.net/zhaohongyan6/article/details/71158522\n",
    "\n",
    "Python信号相关：\n",
    "https://my.oschina.net/guol/blog/136036\n",
    "\n",
    "Linux--进程组、会话、守护进程\n",
    "https://www.cnblogs.com/forstudy/archive/2012/04/03/2427683.html\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
